I'm studying inheritance in JavaScript using prototype chaining.
Here's the code: 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.
Here thief.prototype.__proto__.__proto__ = bank.prototype
breaks and outputs error:
"<a class='gotoLine' href='#47:37'>47:37</a> Uncaught TypeError: Immutable prototype object '#<Object>' cannot have their prototype set"
Since thief.prototype.__proto__ = bank.prototype
works I thought thief.prototype.__proto__.__proto__ = bank.prototype
would work as well.
Can you explain the error and how to fix it? Thanks.
To make thief
inherit all methods and fields from bank
, just set thief.prototype = bank.prototype
. What you are currently using makes no sense; thief.prototype.__proto__
just returns Object.prototype
and the __proto__
of that is just null
(and is not a writable property).
// 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.