user2759694
user2759694

Reputation: 11

Deleting the function.prototype object

In Javascript: the good parts by Douglas Crockford, under section 3.4 Reference, it says that: Objects are passed around by reference. They are never copied, so

a = b = c = {}; // a, b, and c all refer to the same empty object

Following the same lines, suppose I have a parent class P, and I inherit it in a subclass SC something like this,

var P = function (){};

var SC = function (){};

SC.prototype = z = new P();

Now, whatever changes that I make in SC.prototype, same are visible in 'z' as well, which is consistent with book. But if i 'delete z' , then still the SC.prototype object is unaffected (it exists). Why is it not modified/ removed?

Upvotes: 0

Views: 122

Answers (2)

raina77ow
raina77ow

Reputation: 106385

Because with delete something you just erase a binding named something - not an object itself. Quoting the doc (MDN):

Unlike what common beliefs suggests, the delete operator has nothing to do with directly freeing memory (it only does indirectly via breaking references).

BTW, strictly speaking, delete z for z defined as a variable (i.e., with var z) won't have even this effect:

delete is only effective on an object's properties. It has no effect on variable or function names.

Of course, if omitting var here was intentional, z binding will be removed - as it's actually no longer a variable, but a property of a global object instead.


You might say: 'Ok, but what if I delete SC.prototype instead?' Well, you can't: prototype is a non-configurable property of SC (as for any function), so attempt to delete it will just return false in non-strict mode. In strict mode it'll throw an Exception at you.

Upvotes: 1

Joseph Silber
Joseph Silber

Reputation: 219946

deleteing an object reference doesn't touch the object itself; it just clears the reference. The object will then be garbage collected if there's no other reference to it.

Since SC.prototype retains its reference to that object, deleteing z doesn't actually delete the object.

Upvotes: 1

Related Questions