Javascript Function-Pointer Assignment

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)