javascript面向对象编程--安全构造对象

构造函数 其实就是一种 使用new运算符的函数

function Person(name,age,job){

     this.name=name;

    this.age=age;

    this.job=job;

}

var person=new Person("Owen",34,"codeworker");

如果没有new,由于该this对象是在运行时绑定,直接使用Person会将该对象绑定到window上,即this解析成window

解决方案--安全构造对象

function Person(name,age,job){

   if(this instanceof Person){    //检测对象是否为Person的实例

          this.name=name;

          this.age=age;

          this.job=job;

       }   else{

          return new Person(name,age,job)

     }

}

2.继承时导致的不安全问题,如果使用的构造函数获取继承且不使用原型链,这个继承会被破坏

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);//注意,由于Polygond的作用域是安全的,this并非是Polygon的实例,而是返回创建一个新的Polygon对象

    this.width=width;

    this.height=height;

    this.getArea=function(){ return this.width*this.height;}

}

Rectangle.prototype=new Polygon();//增长react的this,

var rect=new Rectangle(5,10);

alert(rect.sides);//2,若没有使用原型链则是undefined

猜你喜欢

转载自blog.csdn.net/wenmin1987/article/details/83449609