If you create a new object using Object.create and specify a prototype in it and make it a prototype constructor, the native constructor will not be overwritten. And if you simply make an object a prototype of a constructor, it will be overwritten. How does this removal occur? I do not understand the logic of rewriting the constructor. Or put the question. Why in the first case the designer did not overwrite, and in the second overwritten?

function Animal() {} function Rabbit() {} Rabbit.prototype = Object.create(Animal.prototype); var rabbit = new Rabbit(); alert( rabbit instanceof Rabbit ); выдаст true Rabbit.prototype = {}; alert( rabbit instanceof Rabbit ); выдаст false! 
  • checked the same rabbit ? - Grundy
  • Yes, the same rabbit is checked - Anton
  • why do you expect the designer to overwrite in the first case ?? - ampawd
  • After the new Rabbit declaration, check the alert (rabbit.constructor === Rabbit); The constructor will be overwritten, but the matter is different. That instanceof is not quite on the constructor is checked, Grundy wrote an algorithm for checking it, I just did not quite understand how instanceof works, but the fact that the constructor is overwritten in both cases is a fact. - Anton

1 answer 1

The instanceof operator runs a sequential prototype check.

And since the prototype in Rabbit changed before the second check, the next check returns false .

In fact, the call to this operator can be described by the following cycle:

 function instanceOf(object, Proto) var proto = Proto.prototype; while(true){ var objectProto = Object.getPrototypeOf(object); if(objectProto == null) return false; if(Object.is(objectProto, proto)) return true; } } 

Thus, it is clear that after the Rabbit prototype change, this cycle continues until the prototype received is null and the operator does not return false .