我正在努力提高我對物件、建構式、原型以及與 JS 中的物件相關的所有內容的知識。我在 MDN 上閱讀了一篇關于繼承和原型鏈的文章,我遇到了關于為什么在創建實體后不應該重新分配 Constructor.prototype 的解釋。我不明白這兩個原因是什么意思:
function Box(value) {
this.value = value;
}
Box.prototype.getValue = function () {
return this.value;
};
const box = new Box(1);
// Mutate Box.prototype after an instance has already been created
Box.prototype.getValue = function () {
return this.value 1;
};
box.getValue(); // 2
他們的解釋:
一個推論是,重新分配 Constructor.prototype( Constructor.prototype = ...) 是一個壞主意,原因有兩個:
在重新分配之前創建的
[[Prototype]]實體現在參考與重新分配之后創建的實體不同的物件[[Prototype]]——改變一個[[Prototype]]不再改變另一個。除非您手動重新設定
constructor屬性,否則無法再從 跟蹤建構式instance.constructor,這可能會破壞用戶的預期。一些內置操作也會讀取該constructor屬性,如果未設定,它們可能無法按預期作業。
uj5u.com熱心網友回復:
文章指的是這種行為:
function Box(value) {
this.value = value;
}
Box.prototype.getValue = function () {
return this.value;
};
const box1 = new Box(1);
// Mutate Box.prototype after an instance has already been created
Box.prototype = {
getValue() {
return this.value 42;
}
}
const box2 = new Box(1);
console.log(box1.getValue()); // 2
console.log(box2.getValue()); // 43
如果您分配一個新值,Box.prototype那么只有新創建的實體才會有這個新值作為它們的原型。如您的示例中那樣改變現有的原型物件不是問題(但仍然不常見)。
除非您手動重新設定
constructor屬性,否則無法再從instance.constructor...跟蹤建構式
比較以下
function Box(value) {
this.value = value;
}
const box1 = new Box(1);
console.log('box1.constructor === Box:', box1.constructor === Box);
Box.prototype = {
getValue() {
return this.value 42;
}
}
const box2 = new Box(1);
console.log('box2.constructor === Box:', box2.constructor === Box);
Box.prototype = {
constructor: Box,
getValue() {
return this.value 42;
}
}
const box3 = new Box(1);
console.log('box3.constructor === Box:', box3.constructor === Box);
除非constructor在分配給 后顯式設定,Box.prototype否則box.constructor不參考Box。
這可能有用:
- 定義 Javascript 原型
- JavaScript 的 Object.prototype 行為是什么?
- JavaScript:instanceof 運算子
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/532085.html
