Kevin Meredith
Kevin Meredith

Reputation: 41909

JavaScript Function Reference

Consider this code, which sets a to a function. Then f points to a, but then a gets set to null.

var a = function () { 
    return 5;
};

var f = a; 

a = null;

However, when calling f(), 5 prints out.

console.log(f());

5

Why doesn't calling f() result in a null object reference?

http://jsfiddle.net/deDca/

Upvotes: 0

Views: 90

Answers (3)

Felix Kling
Felix Kling

Reputation: 816262

(In JavaScript) A variable is like a box that can contain something (var a = ...;). Two boxes can contain the same thing (var f = a;). If you put something else into one of the boxes (a = null), it doesn't change the content of the other box (f), even if it originally contained the same thing.

Upvotes: 0

m59
m59

Reputation: 43745

I'll preface my answer by saying that functions are objects in javascript, so we're really talking about object references in general.

You can't actually null the object in memory. You're only setting a reference to the actual object to null. f is a reference to that object, just like a is. You're making a no longer a reference to that object, but that doesn't affect f at all.

The garbage collector will take care of actually removing the object altogether.

In case that's unclear, I'll explain in other words:

var a = {}; makes an object in memory. a isn't actually that object, but a reference to it.

var f = a means that f now references the same object that a references.

a = null; means that a no longer references the object, but doesn't affect the object itself. f still references that object.

Upvotes: 1

jfriend00
jfriend00

Reputation: 707158

Here's step by step what is happening:

var a = function () { 
    return 5;
};

Assigns a function reference to the variable a.


var f = a; 

Assigns the same function reference to the variable f. At this point, both a and f contain a reference to the same function.


a = null;

Clears a so it no longer contains that function reference. But, f still contains the function reference and has nothing to do with a so you can change the value of a to your heart's content and it will not affect what f has. After the second step above, each variable had it's own unique reference to the function. a and f did not point at each other.

It's like if you have two friends and you tell each of them a secret password. Now, you tell the first friend that the password is now different. The second friend still has the original password - they are not affected by the fact that you told the first friend something different.

Upvotes: 5

Related Questions