如果更換線
Me.prototype.constructor = Me; // Why?
與
console.log(Me.prototype.constructor);
Me.prototype.constructor = Me; // Why?
你會發現,在設置前,Me.prototype.constructor
是You
,因爲Me.prototype
是You
的情況下,由於線
Me.prototype = new You();
所以,與th e // Why?
註釋有必要「修復」這種錯誤的印象,即您以這種方式繼承了JavaScript。
基本上問題出現了,因爲您試圖使用原型繼承來實現經典繼承。原型繼承適用於對象實例,並沒有「類」的概念,甚至沒有「類型」的概念,但JavaScript使整個業務的整個new
,.constructor
和instanceof
業務變得更加混亂。
做這種事情的更原型的方法是避開構造有利於電源的構造,即功能與形式返回一個對象,你的願望:
function begetPart(partNumber, description) {
return Object.create({}, {
number: { value: partNumber },
description: { value: description },
describe: {
value: function() {
alert(this.description);
}
}
});
}
function begetTire(partNumber, speed) {
return Object.create(
begetPart(partNumber, "A tire"),
{
speed: { value: speed },
describe: {
value: function() {
alert(this.description + "; speed = " + this.speed);
}
}
}
);
}
var genericPart = begetPart(1234, "A widget");
genericPart.describe(); // alerts "A widget"
var tire = begetTire(4567, "fast");
tire.describe(); // alerts "A tire; speed = fast"
這裏我們使用Object.create
說「基於這個其他對象實例創建一個對象實例「。另一個實例是一個新的空對象begetPart
和一個新的「零件實例」,其中一些屬性預先填充爲begetTire
。
這更好地反映了JavaScript和原型繼承的實際工作原理,因爲原型繼承對象實例從其他對象實例繼承,沒有整個「類型」或「類」的想法阻礙。
我相信舊式瀏覽器會檢查'instanceof'關鍵字的'.constructor'屬性。 – Raynos
這是一本2006年以來的書。 –