Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is object lifetime in javascript code that uses prototype inheritance?

I am currently reading 'Javascript Good Parts', and I came across the following paragraph

If we try to retrieve a property value from an object, and if the object lacks the property name, then JavaScript attempts to retrieve the property value from the prototype object. And if that object is lacking the property, then it goes to its prototype, and so on until the process finally bottoms out with Object.prototype.

If I create an object obj2 from obj1 as prototype, does that mean obj1 cannot be destroyed until obj2 also goes out of scope?

like image 632
patentfox Avatar asked Jan 17 '12 07:01

patentfox


1 Answers

As long as you've built your object's inheritance (linked the prototypes), I don't think that the browser relies on your references to that object.

ex1 :

var a = function(){};
a.prototype.toString = function(){return "I'm an A!";};
var b = new a();
a = undefined;
var c = new a();// error => a is not a function any more!
b.toString();// it works because the prototype is not destroyed, 
             // only our reference is destroyed

ex2 :

var a = function(){};
a.prototype.toString = function(){return "I'm an A!";};
var b = function(){};
b.prototype = new a();
a = undefined;
var c = new b();
console.log(c+'');// It still works, although our 
                  // initial prototype `a` doesn't exist any more.

UPDATE: This behaviour might be related to the fact that in javascript you can't exactly destroy an object; you can only remove all references to it. After that, the browser decides how to deal with the unreferenced objects through it's Garbage collector.

like image 118
gion_13 Avatar answered Oct 20 '22 09:10

gion_13