when the new object is constructed ,The object is set up to delegate any properties which haven't been explicitly set up to its constructor's prototype. That means that we can change the prototype later, and still see the changes in the instance.
first:
function Foo(){}
foo=new Foo();
Foo.prototype={};
foo.constructor==Foo//true.why is this happening since construtor prototype is empty object
so the statement are not working as per the definition.right or wrong? but if i do this than result is different
second:
function Foo(){}
Foo.prototype={};
foo=new Foo();
foo.constructor==Foo//false as aspected
again third:
function Foo(){}
Foo.prototype={};
Foo.prototype.name="Maizere";
foo=new Foo();
foo.name==Maizere//true.The definition at the top is applying here,if so why the definition not working in the first: example
plz help with simple english.i m really getting headache.
2 Answers 2
why is this happening
The new operator sets the inheritance of the instance to the object that the constructor's prototype property currently points to. So when you do
function Foo() {}
var foo = new Foo;
it is irrelevant if someone assigns to Foo.prototype after that - it will not change foo.
- first: The inherited
constructorproperty you are getting comes from the "old" prototype - an object that is initialized together with the function and having that hidden "constructor" property - second: You are overwriting the
prototypeproperty with an empty object, and yourfoo(created after overwriting) inherits from that. And since empty objects inherit fromObject.prototype, theconstructorproperty now points to theObjectfunction. - third: Again, you create
fooafter overwriting theprototype. Since you assign anameproperty to that new object from whichfooinherits from, you can access it onfooas well.
5 Comments
When you write a function, it comes with a property named prototype - an object whose constructor property is set to the function itself. As you may have known, JavaScript's object model is prototype based. This makes the objects you create with that function inherit all the properties of the prototype of its constructor function (the one you invoke with new) - so you should beware what prototype is the moment you create the object.
In your first case, you are just setting the prototype property of Foo to an empty object. But the original (default) prototype is still referenced by foo. That explains why the last expression evaluates to true.
By the time you create foo in your second case, prototype of Foo has already been set to an empty object. So virtually foo inherits nothing from it. The same principle applies to the third case.
constructor, couldn't you just usefoo instanceof Foo?instanceofwould be ideal for. Unless I'm overlooking something.instanceofwas what you were looking for in case you're trying to solve an issue. In case this is more of a theoretical question about how theconstructorproperty behaves, then these are unrelated.