0

I am learning about JS prototyping and inheritance, I had learned that the right way to do it is by:

function A(){}
A.prototype.doSomething=function(){}
function B(){}
B.prototype = new A();
console.log( (new B()) instanceof A);//true
console.log( (new B()) instanceof B);//true

As you can see I am setting new instance of A into B but as you can see it works great with

function A(){}
A.prototype.doSomething=function(){}
function B(){}
B.prototype = A.prototype;
console.log( (new B()) instanceof A);//true
console.log( (new B()) instanceof B);//true

but here: http://ejohn.org/apps/learn/#76

they claimed that prototype assignment is wrong,I don't understand why?

5
  • try see mdn about instanceof, when you assign prototype, in second case, you don't get B inherit A you get B and A inherit from some other Commented Jan 27, 2015 at 14:02
  • You have a syntax error in 2nd line. Did you mean A.prototype.doSomething = function(){}? Commented Jan 27, 2015 at 14:14
  • @pawel you are right, I had corrected it, thanks! Commented Jan 27, 2015 at 14:22
  • Doing B.prototype = A.prototype; you will have ((new B() instanceof A) == true but also ((new A()) instanceof B) == true, does as Grundy suggested. The site you posted fail in the instanceof test due Ninja.prototype = { dance: Person.prototype.dance }; this break the prototype chain. Commented Jan 27, 2015 at 14:32
  • it breaks it beacuse Ninja.prototype = { dance: Person.prototype.dance }; is reassign the general object into prototype and overrides the assignement Commented Jan 27, 2015 at 15:00

1 Answer 1

1

here is the reason in the first example:

console.log( (new B()) instanceof A);//true

But

console.log( (new A()) instanceof B);//true

So this is wrong usage....
The right way is to do it in the next way:

function Parent(){}
function Child(){}
Child.prototype = Object.create(Parent.prototype); 
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.