8

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?

patentfox
  • 1,436
  • 2
  • 13
  • 28
  • I really don't know how different JavaScript engines implement prototype, but I don't think it's like a **reference** to an object. It's more like an inheritance mechanism, so I would be surprised if an **instance** of obj1 is needed for obj2 to exists. – Michiel van Oosterhout Jan 17 '12 at 07:44

1 Answers1

5

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.

Community
  • 1
  • 1
gion_13
  • 41,171
  • 10
  • 96
  • 108
  • 1
    Hm, wasn't `a` just a reference to that object, just like `b.prototype` is? Seems like we still have a reference. – kapa Jan 17 '12 at 08:07
  • `b.prototype` is an **instance** of `a`. (feel the `new` keyword) – gion_13 Jan 17 '12 at 08:10
  • As a **name** `b.prototype` is certainly a **reference**, `new a()` returnes an unnamed reference to an object, which could be assigned to a named reference, like `b.prototype`, or could be used once and after been used that way it becomes inaccessible (literally goes out of scope). – zuba Mar 06 '13 at 14:24