Javascript - 将函数赋值给变量(引用/值)

时间:2014-02-19 17:14:20

标签: javascript

我正在尝试更改函数的定义:

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

这会导致变量a保持原始分配,即产生alert('a')的函数。

有没有办法传递对javascript函数的引用,以便我以后可以改变它?

3 个答案:

答案 0 :(得分:5)

您希望在以下代码段之后更改a的值吗?有问题的片段:

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

不,对吧?那么为什么您希望将b重新分配给 影响a

在行1之后,您a指向一个函数实例:

enter image description here

在行2之后,您有一个新变量b指向同一个函数实例。所以现在你有两个变量,都指向同一个实例:

enter image description here

在行3之后,您已将b重新分配给其他内容(新功能),但a 仍指向原始功能:< / p>

enter image description here

你可以做这样的事情来做你想做的事:

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

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

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

现在调用a()b()会提醒字符串b

答案 1 :(得分:1)

  

有没有办法传递对javascript函数的引用,以便我以后可以改变它?

没有办法做到这一点。 Javascript没有“指针”。它具有参考,因此a是对a的的引用,而不是对a的内存位置的引用。

所以,对于这套说明

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

这是进展

//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');};

答案 2 :(得分:0)

你可以像这样产生你想要的结果:

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

这段代码会产生您想要的效果,因为它们都会调用fn()并且您正在更改公共底层引用。