简体   繁体   中英

Javascript - assign function to variable (reference/value)

I am trying to change the definition of a function:

var a = function(){alert('a');};
var b = a;
b = function(){alert('b');};

This results in the variable a keeping it's original assignment ie the function producing alert('a') .

Is there any way of passing around a reference to a javascript function so that I can alter it later?

Would you expect the value of a to change after the following snippet? Snippet in question:

var a = 10;
var b = a;
var b = 20;

No, right? So why would you expect reassigning b to also affect a ?

After line 1 , you have a pointing to a function instance:

在此处输入图片说明

After line 2 , you have a new variable b , also pointing to the same function instance. So now you have two variables, both pointing to the same instance:

在此处输入图片说明

After line 3 , you have reassigned b to something else (a new function), but a is still pointing to the original function:

在此处输入图片说明

You can do what you want by doing something like this:

var func = function() { alert("a"); };

var a = function() { func(); };
var b = a;

func = function() { alert("b"); };

Now calling a() or b() will alert the string b .

Is there any way of passing around a reference to a javascript function so that I can alter it later?

There is no way to do this. Javascript does not have "pointers". It has reference values , and as such, a is a reference to the value of a, not to the memory location of a.

So, for this set of instructions

var a = function(){alert('a');};
var b = a;
b = function(){alert('b');};

this is the progression

//a is stored at some memory location
var a;

//b is stored at some memory location
var b;

//the memory location where a is stored has its value updated
a = function(){alert('a');};

//the memory location where b is stored has its value updated
//from the value stored at a's memory location
b = a;

//the memory location where b is stored has its value updated
b = function(){alert('b');};

You could produce the result you're looking for like this:

var fn = function() { alert('a'); };
var a = function() { fn(); };
var b = a;
fn = function(){ alert('b'); };

This code would produce the desired effect you're looking for because they'll both call fn() and you're changing the common underlying reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM