简体   繁体   English

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

[英]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') . 这导致在变量a保持它的原始分配,即功能产生alert('a')

Is there any way of passing around a reference to a javascript function so that I can alter it later? 有什么办法可以绕过对javascript函数的引用,以便以后可以更改它?

Would you expect the value of a to change after the following snippet? 您希望以下代码段后a的值发生变化吗? 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 ? 那么,为什么期望重新分配b 也会影响a呢?

After line 1 , you have a pointing to a function instance: 在第1行之后,您有a指向函数实例a指针:

在此处输入图片说明

After line 2 , you have a new variable b , also pointing to the same function instance. 在第2行之后,您有一个新变量b ,它指向同一函数实例。 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: 在第3行之后,您已经将b重新分配给其他功能(新功能),但是a 仍指向原始功能:

在此处输入图片说明

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 . 现在调用a()b()将提醒字符串b

Is there any way of passing around a reference to a javascript function so that I can alter it later? 有什么办法可以绕过对javascript函数的引用,以便以后可以更改它?

There is no way to do this. 没有办法做到这一点。 Javascript does not have "pointers". Javascript没有“指针”。 It has reference values , and as such, a is a reference to the value of a, not to the memory location of a. 它具有参考 ,因此, a是对a的的引用,而不是对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. 该代码将产生您想要的效果,因为它们都将调用fn(),并且您正在更改通用的基础引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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