JavaScript构造函数详解

来源:互联网 发布:defender 禁止软件联网 编辑:程序博客网 时间:2024/05/20 19:18

构造函数就是初始化一个实例对象,对象的prototype属性是继承一个实例对象。

  构造函数注意事项:

1.默认函数首字母大写

2.构造函数并没有显示返回任何东西。new 操作符会自动创建给定的类型并返回他们,当调用构造函数时,new会自动创建this对象,且类型就是构造函数类型。

3.也可以在构造函数中显示调用return.如果返回的值是一个对象,它会代替新创建的对象实例返回。如果返回的值是一个原始类型,它会被忽略,新创建的实例会被返回。    

1
2
3
4
functionPerson( name){
       this.name =name;
     }
      varp1=newPerson('John');

等同于:

1
2
3
4
5
6
functionperson(name ){
     Object obj =newObject();
     obj.name =name;
      returnobj;
   }
    varp1= person("John");

4.因为构造函数也是函数,所以可以直接被调用,但是它的返回值为undefine,此时构造函数里面的this对象等于全局this对象。this.name其实就是创建一个全局的变量name。在严格模式下,当你补通过new 调用Person构造函数会出现错误。

 

5.也可以在构造函数中用Object.defineProperty()方法来帮助我们初始化:

1
2
3
4
5
6
7
8
9
10
11
12
13
functionPerson( name){
      Object.defineProperty(this,"name"{
        get :function(){
           returnname;
        },
         set:function(newName){
          name =newName;
        },
        enumerable :true,//可枚举,默认为false
         configurable:true//可配置
       });
    
     varp1=newPerson('John');

6.在构造函数中使用原型对象      

1
2
3
4
//比直接在构造函数中写的效率要高的多
      Person.prototype.sayName=function(){
        console.log(this.name);
     };

但是如果方法比较多的话,大多人会采用一种更简洁的方法:直接使用一个对象字面形式替换原型对象,如下:      

1
2
3
4
5
6
7
8
Person.prototype ={
       sayName :function(){
          console.log(this.name);
       },
       toString :function(){
          return"[Person "+this.name+"]";
       }
     };

这种方式非常流行,因为你不用多次键入Person.prototype,但有一个副作用你一定要注意:

使用字面量形式改写了原型对象改变了构造函数的属性,因此他指向Object而不是Person。这是因为原型对象具有一个constructor属性,这是其他对象实例所没有的。当一个函数被创建时,它的prototype属性也被创建,且该原型对象的constructor属性指向该函数。当使用对象字面量形式改写原型对象时,其constructor属性将被置为泛用对象Object.为了避免这一点,需要在改写原型对象的时候手动重置constructor,如下:

1
2
3
4
5
6
7
8
9
10
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

原创粉丝点击