Rohit Goyal
Rohit Goyal

Reputation: 222

Inheriting properties from prototype

function classA(){}; 

classA.prototype.age =25;

var obj = new classA();

console.log(obj.age)  //returns 25

Now, when I do:

classA.prototype = {};

Why obj.age is still returning 25?

Upvotes: 1

Views: 51

Answers (3)

nem035
nem035

Reputation: 35481

This is happening because you pointed the classA.prototype to a new object but you didn't change the object that obj.prototype points to.

What is happening is:

classA.prototype ------> A
// create object with new classA()
// now its prototype also points to A
obj.prototype    ------> A    // points to the same prototype

now you reasign the prototype of classA

classA.prototype ------> B

but the prototype of obj still points to A (it was never changed)

obj.prototype    ------> A

So all you did was change the prototype reference of classA after the prototype reference for obj was already established.

If you want to have obj see the changes on the prototype, then change the object it references (A in the example above) and not the reference itself:

Sample code:

function classA(){}; 

classA.prototype.age =25;

var obj = new classA();

console.log(obj.age)   // 25

// change the object itself, not the reference
delete classA.prototype.age;

console.log(obj.age); // undefined

Upvotes: 1

Ramanlfc
Ramanlfc

Reputation: 8354

reassigning your prototype after creating the object has no effect on the previously created object , it will still have the old prototype when it was created. New prototye will only effect newly created objects

Upvotes: 0

Matthias Holdorf
Matthias Holdorf

Reputation: 1050

If your code is in the following order:

function classA(){}; 

classA.prototype.age = 25;
classA.prototype = {};

var obj = new classA();
console.log(obj.age)  // returns undefined

The result will be indeed your excepted behavior. It depends on when you set the prototype of the classA function. This will be demonstrated by the following code snippet:

function classA(){}; 

classA.prototype.age = 25;

var obj1 = new classA();

classA.prototype = {};

var obj2 = new classA();

console.log(obj1.age)  // returns 25
console.log(obj2.age)  // returns undefined

Hence, a object is only affected by the changes to a prototype of a function, when this happens before the object's creation.

Upvotes: 0

Related Questions