简体   繁体   中英

Strange javascript prototypal inheritance

JavaScript gurus, here is a puzzle for you:

function aFunc(){}
function bFunc() {}
aFunc.prototype = bFunc.prototype;
a = new aFunc();
console.log(a instanceof bFunc); //true!

Why is a instance of bFunc ?

I could understand this if it was like so:

function aNext(){}
function bNext(){}
aNext.prototype = new bNext();
a = new aNext();
console.log(a instanceof bNext);

..but with prototypes it seems very strange to me. Practical applications of prototypal code above you can find in Professional JavaScript for Web Developers book (ch 6, last pages).

Edit: Thanks Blender, but here respectively comes new riddle: now if we have 2 objects that are inherited from single same object they are instanceof each other (but they are completely different)!

function Horse(){} //class chain can be very long
function Pig(){}
Horse.prototype = Object.prototype;
Pig.prototype = Object.prototype;
a = new Pig();
console.log(a instanceof Horse); //true!

How can we solve issue? How can I determine that pig is not a horse, if they all are animals (have same prototypes in the past)?

From the MDN :

The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.

So in your case, it tests whether bFunc.prototype is in the prototype chain of a . Since bFunc.prototype === a.prototype , it'll return true .

答案是:pig_instance.prototype = Object.prorotype = horse_instance.prototype,因此Pig和Horse来自同一原型,instanceof对此进行检查并返回TRUE。

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