javascript深入理解系列(三)——constructor

prototype對象有一個構造函數,默認指向prototype對象所在的構造函數

function Person(name,age){
            this.name=name;
            this.age=age;
        }
        var xiaoming=new Person("小明",10);
        console.log(Person.prototype.constructor==Person);

因爲constructor屬性定義在prototype上面,所以可以被構造函數的所有實例對象使用

console.log(xiaoming.constructor===Person);

xiaoming本身並沒有constructor屬性,而是繼承的其原型鏈上的constructor

constructor的作用是可以知道實例對象的構造函數是誰

constructor屬性表示原型對象與構造函數之間的關聯關係,如果修改了原型對象,一般會同時修改constructor屬性,防止引用的時候出錯。

function Person(name,age){
            this.name=name;
            this.age=age;
        }
        var xiaoming=new Person("小明",10);
        Person.prototype={
            say:function(){
                console.log("說話");
            }
        }
        console.log(Person.prototype.constructor==Person);//輸出false

因爲Person.prototype指向了普通對象,普通對象的prototype.constructor指向Object

console.log(Person.prototype.constructor==Object);//輸出true

所以,修改原型對象時,一般要同時修改constructor屬性的指向。

// 壞的寫法
C.prototype = {
  method1: function (...) { ... },
  // ...
};

// 好的寫法
C.prototype = {
  constructor: C,
  method1: function (...) { ... },
  // ...
};

// 更好的寫法
C.prototype.method1 = function (...) { ... };
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章