Javascript Function-Pointer Assignment

JavascriptFunction Pointers

Javascript Problem Overview


Consider this javascript code:

var bar = function () { alert("A"); }
var foo = bar;
bar = function () { alert("B"); };
foo();

When running this code I get "A". Is this behavior a part of javascript specification and can I rely on it?

Javascript Solutions


Solution 1 - Javascript

In other examples, nothing was passed by value; everything was passed by reference.

bar and foo are BOTH pointers

All vars/handles to NON primitive objects in javascript are pointers; pointers ARE native to javascript, they are the default.

var bar = function () { alert("A"); } //bar is a pointer to function1
var foo = bar;  //pointer copied; foo is now also a pointer to function1
bar = function () { alert("B"); };  //bar points to function2
foo();  //foo is still a pointer to function1

You will run into hidden errors and bugs if you think they are copies. Especially so if you work with complex objects. For example

function person(name){this.name = name}
var john = new person("john")
var backup = john
backup.name //john
john.name = "jack"
backup.name //jack, NOT john

To really COPY a non-primitive in javascript takes more work than just a = b. For example:

function person(name){	this.name = name}
var john = new person("john")
var backup = new Object()
backup = JSON.parse(JSON.stringify(john))
backup.__proto__ = john.__proto__	//useful in some cases
john.name = "jack"
backup.name //john

Solution 2 - Javascript

Yes that is expected and by design.

Your question is basically: does foo reference bar as a pointer or reference would in another language?

The answer is no: the value of bar at the time of assignment is assigned to foo.

Solution 3 - Javascript

I'm a bit late here but I thought I'd give an answer anyways and flesh something out.

It's best not to think in terms of pointers and memory references when discussing the internals of JavaScript (or ECMAScript) when dealing with the specifications. Variables are environment records internally and are stored and referenced by name, not memory address. What your assignment statement is doing, internally and by design, is looking up the environment record name (either "foo" or "bar") and assigning the value to that record.

So,

var bar = function () { alert("A"); }

is assigning the environment record "bar" the value (anonymous function).

var foo = bar;

internally calls GetValue("bar") which retrieves the value associated with the record "bar" and then associates that value with the record "foo". Hence, afterwards the original value of bar can still be used as it's now associated with foo.

Because JavaScript references by string and not memory address is precisely why you can do things like this:

someObject["someProperty"]

which is looking up the value based on the property name.

Solution 4 - Javascript

You are assigning the value of an anonymous function to a variable not a pointer.
If you want to play with pointers, you can use objects that are passed by reference, not copy.

Here are some examples:

"obj2" is a reference of "obj1", you change "obj2", and "obj1" is changed. It will alert false:

var obj1 = {prop:true},
    obj2 = obj1;
obj2.prop = false;
alert(obj1.prop);


"prop" points to a property that is not an object, "prop" is not a pointer to this object but a copy. If you change "prop", "obj1" is not changed. It will alert true:

var obj1 = {prop:true},
    prop = obj1.prop;
prop = false;
alert(obj1.prop);

"obj2" is a reference to the "subObj" property of "obj1". if "obj2" is changed, "obj1" is changed. It will alert false:

var obj1 = {subObj:{prop:true}},
    obj2 = obj1.subObj;
obj2.prop = false;
alert(obj1.subObj.prop);

Solution 5 - Javascript

Yes, there's nothing special about the fact that the variables are referring to functions, there's no aliasing involved.

var bar = 1;
var foo = bar;
bar = "something entirely different";
// foo is still 1

Solution 6 - Javascript

Yes, this is the correct behavior.

//create variable bar and assign a function to it
var bar = function () { alert("A"); }
//assign value of bar to the newly created variable foo
var foo = bar;
//assign a new function to the variable bar
//since foo and bar are not pointers, value of foo doesn't change
bar = function () { alert("B"); };
//call the function stored in foo
foo();

Solution 7 - Javascript

Those are not function pointers (and there are no pointers in JS natively). Functions in JS can be anonymous and are first class objects. Hence

function () { alert("A"); }

creates an anonymous function that alerts "A" on execution;

var bar = function () { alert("A"); };

assign that function to bar;

var foo = bar;

assign foo to bar, which is the function "A".

bar = function () { alert("B"); };

rebind bar to an anonymous function "B". This won't affect foo or the other function "A".

foo();

Call the function stored in foo, which is the function "A".


Actually in languages where there are function points e.g. C it won't affect foo either. I don't know where you get the idea of getting "B" on reassignment.

void A(void) { printf("A\n"); }
void B(void) { printf("B\n"); }
typedef void(*fptr_t)(void);
fptr_t foo = A;
fptr_t bar = foo;
bar = B;
foo(); // should print "A"

Solution 8 - Javascript

This is assigning a variable to an unnamed function, not a pointer to a function

Solution 9 - Javascript

Yes, you've created a pointer to the original "A" function. When you reassign bar, you're reassigning it, but you're still leaving any references to the old function alone.

So to answer your question, yes, you can rely on it.

Solution 10 - Javascript

I would just like to add this also works for pre-defined named functions as well:

function myfunc() { alert("A"); }
var bar = myfunc;
var foo = bar;
bar = function () { alert("B"); };
foo();

This will do the same thing, indicating that function names act like array names (pointers).

Solution 11 - Javascript

>For each FunctionDeclaration f in code, in source text order do: > >Let fn be the Identifier in FunctionDeclaration f. > >Let fo be the result of instantiating FunctionDeclaration f as described in Clause 13. > >Let funcAlreadyDeclared be the result of calling env’s HasBinding concrete method passing fn as the argument. > >If funcAlreadyDeclared is false, call env’s CreateMutableBinding concrete method passing fn and configurableBindings as the arguments.

References

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionniaherView Question on Stackoverflow
Solution 1 - JavascriptsiingCoderView Answer on Stackoverflow
Solution 2 - JavascriptcletusView Answer on Stackoverflow
Solution 3 - JavascriptBobView Answer on Stackoverflow
Solution 4 - JavascriptMicView Answer on Stackoverflow
Solution 5 - JavascriptpolygenelubricantsView Answer on Stackoverflow
Solution 6 - JavascriptAmarghoshView Answer on Stackoverflow
Solution 7 - JavascriptkennytmView Answer on Stackoverflow
Solution 8 - JavascriptSvetlozar AngelovView Answer on Stackoverflow
Solution 9 - JavascriptDavid MortonView Answer on Stackoverflow
Solution 10 - Javascriptuser3015682View Answer on Stackoverflow
Solution 11 - JavascriptPaul SweatteView Answer on Stackoverflow