[英]javascript the passed anonymous function does not change value of parameters
I used anonymous function as parameter in another function, and the anonymous function itself has parmeters also.When the another function is running, and the anonymous func does not work as I expected.I was coufused, can you help? 我在另一个函数中使用匿名函数作为参数,并且匿名函数本身也具有参数。当另一个函数运行时,匿名函数无法按我预期的那样工作,我很困惑,能帮上忙吗? The code is below:
代码如下:
function go(x, func){
func(x);
alert(x.x);
}
var x = {'x': 3};
go(x, function(x){x = {'x':99};});//actually it alert 3, not 99, x not change
go(x, function(x){x.x = 7;}); //it behaves normal, alert 7, not 3
What is x ? 什么是x?
var x = {'x': 3};
x is variable which is a reference to the actual value of the object. x是变量,是对对象实际值的引用。
First Scenario: 第一种情况:
go(x, function(x){x = {'x':99};});//actually it alert 3, not 99, x not change
When the function is invoked using func(x);
使用
func(x);
调用func(x);
the value of reference is passed by value Following activities happen 参考值通过值传递
x
is created x
x
, effectively x contains a reference of the global variable x. x
,有效地x包含全局变量x的引用。 x = {'x':99};
x = {'x':99};
it will just create a new Object {'x':99}
and assign the new reference of the new Object to x. {'x':99}
并将新对象的新引用分配给x。 Hence, x (step 1) is pointing to a new object, which has value of x as 99. alert(xx);
alert(xx);
x is pointing to global object and since the global object x is not modified the value of xx
is still 3 . xx
的值仍为3 。 Second Scenario: 第二种情况:
go(x, function(x){xx = 7;}); //it behaves normal, alert 7, not 3
First few steps are similar 前几个步骤相似
x
is created x
x
, effectively x contains a reference of the global variable x. x
,有效地x包含全局变量x的引用。 {xx = 7;}
is actually a kind of dereference or you are trying to fetch the value of the global object x
and then assigning a new value of 7 to the global object x
property x
. {xx = 7;}
实际上是一种取消引用,或者您试图获取全局对象x
的值,然后将新值7分配给全局对象x
属性x
。 You are modifying the global object and not changing the reference of x to a new object as was done in the first scenario. x
. x
。 alert(xx);
alert(xx);
The x is the global object, but in this case the value of xx
(global) has been modified by the anonymous function. xx
(全局)的值已由匿名函数修改。 The difference is how JS interprets the codes x = { x: 99}
and xx = 7
The first code means that you create completely new anonymous object {x: 99}
, and then change the reference of the global variable x
to this object. 区别在于JS解释代码
x = { x: 99}
和xx = 7
。第一个代码意味着您创建了一个全新的匿名对象{x: 99}
,然后将全局变量x
的引用更改为该对象。 Meanwhile the second code just gets the reference to the global variable x
and change it's property. 同时,第二个代码只是获取对全局变量
x
的引用并更改其属性。 That's it :) 而已 :)
For explanations see above anwers. 有关说明,请参见上面的答案。 This is a fix to your problem:
这是解决您的问题的方法:
function go(x, func){
x=func(x)||x;
alert(x.x);
}
var x = {'x': 3};
go(x, function(x){return {'x':99};});//works now
go(x, function(x){x.x = 7;}); //it behaves normal, alert 7, not 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.