4

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 '#&lt;Object&gt;' 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.

5
  • @hev1 to demonstrate prototype chain. Commented Jul 14, 2020 at 1:00
  • Why not just thief.prototype = bank.prototype;? jsfiddle.net/f71dcbt4 Commented Jul 14, 2020 at 1:01
  • @hev1 so it goes up prototype chain of thief multiple times to find steal() method. just for demonstration. Commented Jul 14, 2020 at 1:02
  • Using it makes no sense; thief.prototype.__proto__ just returns Object.prototype. And the __proto__ of that is just null. Commented Jul 14, 2020 at 1:05
  • Please don't use jsfiddle when you can use a Stack Snippet Commented Jul 14, 2020 at 1:19

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.