I am unable to understand this loop behavior of the javascript.
Can someone tell me why was it designed in this way?
Is there any real use case of this behavior?
why this loop? {
Newly created instance inherits properties from the prototype property of the constructor function object.
prototype property of the constructor function is an object that keeps constructor property.
constructor property is equal to the constructor function object.
Again constructor function object keeps prototype property.
}
instance1—inhertis(keeps)–>Prototype property of func()–>keep constructor property–>function object func–>keep prototype property.
var func = function(){};
var construct = func.prototype.constructor;
console.log(construct === func); //true
var instance1 = new func();
Updated: Even if in between i assigned something else, instanceof always returns true.
var func1 = function(){};
func1.prototype.constructor = 1;
var instance1 = new func1();
console.log(instance1 instanceof func1); //true
var func2 = function(){};
func2.prototype.constructor = 0;
var instance2 = new func2();
console.log(instance2 instanceof func2); //true
Sorry to ask 2 question in 1 but both may be related.
Of course it retains the instance. Why wouldn’t it? If you’re making a duck, it’s a duck – its DNA says that it’s a duck, no matter if you paint it black or teach it to be a goose.
Also, in your case, setting the constructor has no effect. When you do
new func(ornew func(), which are identical), you go and grab an internal property of the function (the[[Construct]]property), and notfunc.prototype.constructor.obj.constructoris defined on every single object, since it’s defined on every “constructor”: That is,Object Number Function Date Boolean Stringand so on. Each have aconstructorproperty in their prototype:Each one has its
prototype.constructorpointing to itself.Since functions can also behave like constructors, their
.prototype.constructorproperty points to themselves as well. AFAIK, that’s unused in the language itself.The terse, technical answer? http://es5.github.com/#x11.8.6
(slightly paraphrased)
Basically, you’re asking mother-duck: “Excuse me ma’am, is this your child?” The child has little say in the matter.
Edit: As mentioned in the comments, changing the prototype does indeed affect the
instanceofresults. Like above, there’s the intuitive answer and the technical answer.Intuitive answer is simple: The prototype defines the object. Therefore, changing the prototype changes the DNA – you make the duck a goose, not by teaching it to be a goose, but by going to its DNA and changing it to a goose DNA.
The technicality is seeing what
[[HasInstance]]does. (the other[[HasIntsance]]calls this one) The spec is really dry and terse, so here’s the algorithm written in pseudo-javascript:As can be seen, by changing the prototype, we’re changing the behavior –
valuewill be different values.