prototype對象有一個構(gòu)造函數(shù)嗡呼,默認指向prototype對象所在的構(gòu)造函數(shù)
function Person(name,age){
this.name=name;
this.age=age;
}
var xiaoming=new Person("小明",10);
console.log(Person.prototype.constructor==Person);
因為constructor屬性定義在prototype上面桐汤,所以可以被構(gòu)造函數(shù)的所有實例對象使用
console.log(xiaoming.constructor===Person);
xiaoming本身并沒有constructor屬性耳璧,而是繼承的其原型鏈上的constructor
constructor的作用是可以知道實例對象的構(gòu)造函數(shù)是誰
constructor屬性表示原型對象與構(gòu)造函數(shù)之間的關聯(lián)關系囱挑,如果修改了原型對象凌唬,一般會同時修改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 (...) { ... };