我正在使用原型(prototype)链研究 JavaScript 中的继承。
这是代码:https://jsfiddle.net/pnyf1ska/6/
// INHERITANCE USING JS
// SUPER CLASS CONSTRUCTOR
function bank () {
this.cash = 1000;
}
// SUB CLASS CONSTRUCTOR
function thief () {
// CALL BANK CONSTRUCTOR
bank.call(this);
}
// ADD A METHOD TO BANK.PROTOTYPE
bank.prototype.steal = function () {
console.log('a thief stole '+this.cash+' dollars!');
}
// THIEF EXTENDS BANK AND INHERITS STEAL METHOD.
//thief.prototype = bank.prototype;
// thief.prototype.__proto__ = bank.prototype // also works!
thief.prototype.__proto__.__proto__ = bank.prototype; // why does this break?
let t = new thief();
t.steal(); // OUTPUT 1000.
这里thief.prototype.__proto__.__proto__ = bank.prototype
中断并输出错误:"<a class='gotoLine' href='#47:37'>47:37</a> Uncaught TypeError: Immutable prototype object '#<Object>' cannot have their prototype set"
由于thief.prototype.__proto__ = bank.prototype
我想的作品thief.prototype.__proto__.__proto__ = bank.prototype
也可以。你能解释一下这个错误以及如何解决它吗?谢谢。
最佳答案
制作 thief
继承 bank
的所有方法和字段, 只需设置 thief.prototype = bank.prototype
.您当前使用的内容毫无意义; thief.prototype.__proto__
只返回 Object.prototype
和 __proto__
其中只是null
(并且不是可写属性)。
// INHERITANCE USING JS
// SUPER CLASS CONSTRUCTOR
function bank () {
this.cash = 1000;
}
// SUB CLASS CONSTRUCTOR
function thief () {
// CALL BANK CONSTRUCTOR
bank.call(this);
}
// ADD A METHOD TO BANK.PROTOTYPE
bank.prototype.steal = function () {
console.log('a thief stole '+this.cash+' dollars!');
}
thief.prototype = bank.prototype;
let t = new thief();
t.steal(); // OUTPUT 1000.
关于javascript - 在 Javascript 中分配原型(prototype)链会引发 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62886490/