Javascript Function-Pointer Assignment

niaher picture niaher · Feb 24, 2010 · Viewed 63.4k times · Source

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?

Answer

siingCoder picture siingCoder · Jul 22, 2012

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