js 高级函数 之示例

时间:2023-03-08 16:42:11

js 高级函数
作用域安全构造函数

function Person(name, age)
    {
        this.name = name;
        this.age = age;
    }
    var person1 = Person("lin3615", 26);
    //alert(window.name); // lin3615
    alert(person1.name); // 出错,此时成了全局的了
========================
    function Person(name, age)
    {
        this.name = name;
        this.age = age;
    }
    var person1 = new Person("lin3615", 26);
    //alert(window.name);  // 为空
    alert(person1.name); // lin3615
================
为了防止没有使用 new 时实例化,出现跨域,可用以下方法
    function person(name, age)
    {
        if(this instanceof person)
        {
            this.name = name;
            this.age = age;
        }else
        {
            return new person(name,age);
        }
    }
    var person1 = person("lin3615", 26);
    //alert(window.name); // 为空
    alert(person1.name); // lin3615

=========================
以下代码中 Polygon 构造函数是安全的,然后 Rectangle 构造函数则不是,一个 Rectangle 实例之后,这个实例应该通过
Polygon.call() 来继承 Polygon 的 sides 属性。但由于 Polygon
构造函数是作用域是安全的, this 对象并非 Polygon 的实例。所以
会创建并返回一个新的 Polygon 对象

function Polygon(sides)
    {
        if(this instanceof Polygon)
        {
                this.sides = sides;
                this.getArea = function (){
                        return 0;
                    };
        }else
        {
            return new Polygon(sides);
        }
    }
    
    function Rectangle(width, height)
    {
        Polygon.call(this, 2);
        this.width = width;
        this.height = height;
        this.getArea = function(){
                return this.width *

this.height;
            };
    }

var rect = new Rectangle(5, 10);
    alert(rect.sides); // undefined

如果结合原型链则可以解决这个问题

function Polygon(sides)
    {
        if(this instanceof Polygon)
        {
                this.sides = sides;
                this.getArea = function (){
                        return 0;
                    };
        }else
        {
            return new Polygon(sides);
        }
    }
    
    function Rectangle(width, height)
    {
        Polygon.call(this, 2);
        this.width = width;
        this.height = height;
        this.getArea = function(){
                return this.width *

this.height;
            };
    }
    
    Rectangle.prototype = new Polygon();
    var rect = new Rectangle(5, 10);
    alert(rect.sides); // 2