Maizere Pathak
Maizere Pathak

Reputation: 301

javascript:prototype

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.

Upvotes: 1

Views: 81

Answers (2)

Dale Z
Dale Z

Reputation: 517

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.

Upvotes: 1

Bergi
Bergi

Reputation: 664164

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 constructor property 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 prototype property with an empty object, and your foo (created after overwriting) inherits from that. And since empty objects inherit from Object.prototype, the constructor property now points to the Object function.
  • third: Again, you create foo after overwriting the prototype. Since you assign a name property to that new object from which foo inherits from, you can access it on foo as well.

Upvotes: 3

Related Questions