JavaScript類と継承constructor属性

3031 ワード

constructor属性は常に現在のオブジェクトを作成するコンストラクタを指します.たとえば、次の例:たとえば、次の例:
 
  
// var foo = new Array(1, 56, 34, 12);
var arr = [1, 56, 34, 12];
console.log(arr.constructor === Array); // true
// var foo = new Function();
var Foo = function() { };
console.log(Foo.constructor === Function); // true
// obj
var obj = new Foo();
console.log(obj.constructor === Foo); // true
// ,
console.log(obj.constructor.constructor === Function); // true
しかし、コンストラクタがプロトタイプに出会うと、面白いことが起こります.
各関数にはデフォルトの属性プロトタイプがあることを知っていますが、このプロトタイプのconstructorはデフォルトでこの関数を指しています.次の例に示します
 
  
function Person(name) {
this.name = name;
};
Person.prototype.getName = function() {
return this.name;
};
var p = new Person("ZhangSan");
console.log(p.constructor === Person); // true
console.log(Person.prototype.constructor === Person); // true
//
console.log(p.constructor.prototype.constructor === Person); // true
関数のprototypeを再定義すると、constructor属性の挙動がおかしいです.
 
  
function Person(name) {
this.name = name;
};
Person.prototype = {
getName: function() {
return this.name;
}
};
var p = new Person("ZhangSan");
console.log(p.constructor === Person); // false
console.log(Person.prototype.constructor === Person); // false
console.log(p.constructor.prototype.constructor === Person); // false
なぜですか
Person.prototypeを上書きする場合、下記のコード操作を行うことと等価です.
 
  
Person.prototype = new Object({
getName: function() {
return this.name;
}
});
construct属性は常に自分自身のコンストラクションを作成することを指しています.だから、このときPerson.prototype.com nstructor==Objectは次の通りです.
 
  
function Person(name) {
this.name = name;
};
Person.prototype = {
getName: function() {
return this.name;
}
};
var p = new Person("ZhangSan");
console.log(p.constructor === Object); // true
console.log(Person.prototype.constructor === Object); // true
console.log(p.constructor.prototype.constructor === Object); // true
この問題をどう修正しますか?方法も簡単です.Person.prototype.com nstructorを上書きすればいいです.
 
  
function Person(name) {
this.name = name;
};
Person.prototype = new Object({
getName: function() {
return this.name;
}
});
Person.prototype.constructor = Person;
var p = new Person("ZhangSan");
console.log(p.constructor === Person); // true
console.log(Person.prototype.constructor === Person); // true
console.log(p.constructor.prototype.constructor === Person); // true