function F() { } function G() { } var p = {}; F.prototype = p; G.prototype = p; var f = new F(); var g = new G(); //alert(f instanceof F); // returns true, все ясно //alert(f instanceof G); // returns true, почему так?? они ведь даже никак не связаны //alert(g instanceof F); // returns true, почему так?? //alert(g instanceof G); // returns true, все ясно F.prototype = {}; alert(f instanceof F); // returns false, почему так?? g.__proto__ = {}; g instanceof G; // returns false, почему так?? |
1 answer
the whole point is how the instanceof operator works - it compares the prototype of an object with the prototype property of the constructor (and then the prototype prototype with the prototype property of the constructor, etc., until null)
f instanceof F <==> f.__proto__ === F.prototype so you have the F and G constructors in the prototype property containing a link to the same object, so all objects generated by these constructors using new will also have a prototype link to this object when you do:
F.prototype = {}; you change the reference to another object, and object f contains a reference to the old prototype. in case of
g.__proto__ = {}; the same, but vice versa.
|