如果聽起來像你想知道爲什麼它的行爲是這樣,而不只是「修復」代碼。所以這就是發生了什麼。正如你所看到的,如果你改變了「容器」的原型,你實際上會改變已經實例化的新對象和對象的屬性。所以:
function Container(param) {
this.member = param;
}
var newc = new Container('abc');
// setting a new property of the prototype, after newc instantiated.
Container.prototype.stamp = function (string) {
return this.member + string;
}
// This already-instantiated object can access the stamp function
document.write(newc.stamp('123')); // output: abc123
因此,有上述沒有問題,只要它被定義之前,你不叫新方法。下一點。此添加到上述:
// Our Box object
function Box() {
this.color = "red";
this.member = "why";
}
Container.prototype = new Box();
var newd = new Container('fgh');
document.write(newd.stamp('456')); // output: ERROR
錯誤!但這是有道理的,對吧?你完全消滅了「容器」原型,並將其替換爲「盒子」中沒有「印章」功能的原型。
我打算假設你想要「盒子」從「容器」繼承。這從命名慣例是合乎邏輯的。如果你想這樣做,這個替換上一節:
// Our Box object
function Box() {
this.color = "red";
this.member = "why";
}
// This inherits from Container. Note that we can
// do this before or after we declare "Box"
Box.prototype = new Container();
Box.prototype.test = "Whatever";
var b = new Box("jkl"); // note: "jkl" is ignored because "Box" sets "member" to "why"
document.write(b.test); // output: Whatever
document.write("<br>");
document.write(b.stamp("345")); // output: why345
所以現在我們有一個「盒子」,它可以調用自己的方法和參數,並從其父「容器」給他們打電話。
所以,大的情況是,一個對象會查看它自己的方法或原型的原型,如果它沒有找到它,它會看到它繼承的東西的原型,等等。另一個重點是在原型中設置一些東西使得它可以立即在該對象的所有將來和當前實例中使用。
作爲@The Scrum Meister說,你在實例創建後設置'Container'的'prototype'。該實例仍將指向舊的原型。 –
你可以評論你的問題的答案,你不必「編輯」答案。 –
@FelixKling我不認爲你可以評論,如果你有1的評價:s – Neil