JavaScript-函数篇-002(Javascript构造函数)

xiaoxiao2021-02-28  111

github地址:https://github.com/liYinFeng2/javaScript/edit/master/JavaScript分类/函数篇/001_Javascript构造函数.txt

构造函数注意事项: (1).默认函数首字母大写 (2).构造函数并没有显示返回任何东西。new 操作符会自动创建给定的类型并返回他们,当调用构造函数时,new会自动创建this对象,且类型就是构造函数类型。 (3).也可以在构造函数中显示调用return.如果返回的值是一个对象,它会代替新创建的对象实例返回。如果返回的值是一个原始类型,它会被忽略,新创建的实例会被返回。  function Person( name){     this.name =name;  }  var p1=new Person('John'); 等同于:      function person(name ){    Object obj =new Object();    obj.name =name;    return obj;  }  var p1= person("John"); (4).因为构造函数也是函数,所以可以直接被调用,但是它的返回值为undefine,此时构造函数里面的this对象等于全局this对象。 this.name其实就是创建一个全局的变量name。在严格模式下,当你通过new 调用Person构造函数会出现错误。 (5).也可以在构造函数中用Object.defineProperty()方法来帮助我们初始化:  function Person( name){    Object.defineProperty(this, "name"{      get :function(){        return name;      },      set:function (newName){        name =newName;      },      enumerable :true, //可枚举,默认为false      configurable:true //可配置    });  }  var p1=new Person('John'); (6).在构造函数中使用原型对象  //比直接在构造函数中写的效率要高的多  Person.prototype.sayName= function(){    console.log(this.name);  }; 但是如果方法比较多的话,大多人会采用一种更简洁的方法:直接使用一个对象字面形式替换原型对象,如下:  Person.prototype ={     sayName :function(){       console.log(this.name);     },     toString :function(){       return "[Person "+ this.name+"]" ;     }   }; 这种方式非常流行,因为你不用多次键入Person.prototype,但有一个副作用你一定要注意:   使用字面量形式改写了原型对象改变了构造函数的属性,因此他指向Object而不是Person。这是因为原型对象具有一个constructor属性,这是其他对象实例所没有的。当一个函数被创建时,它的prototype属性也被创建,且该原型对象的constructor属性指向该函数。当使用对象字面量形式改写原型对象时,其constructor属性将被置为泛用对象Object.为了避免这一点,需要在改写原型对象的时候手动重置constructor,如下:  Person.prototype ={    constructor :Person,    sayName :function(){      console.log(this.name);    },    toString :function(){      return "[Person "+ this.name+"]" ;    }  };   再次测试:  p1.constructor===Person  true  p1.constructor===Object  false  p1 instanceof Person  true
转载请注明原文地址: https://www.6miu.com/read-60584.html

最新回复(0)