简体   繁体   中英

js inheritance and prototype assignment

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?

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM