在对象文字中,在函数定义中,我调用另一个函数并将函数定义传递给它。
...
var myObjLiteral = {
...
, check_on: function(param1, param2) {
ref.otherFunction(param1, function(param2){checkJson(param2)});
}
}
otherFunction 将按原样接收 param1,但不会按原样接收 param2。
为什么?
因为传递给其他函数的第二个参数创建了它自己的闭包,而 param2 实际上是一个新引用,它覆盖了 check_on 定义中 param2 的外部引用。
我认为这是正确的。但更重要的是,如何将 param2 的值传递到我作为第二个参数传递到 otherFunction 的函数定义中?
谢谢
最佳答案
去掉param2参数即可,(anotherParam不是必需的,只是为了说明问题)
otherFunction(param1, function(anotherParam) {
checkJson(param2);
});
因此该函数将成为 param2 的闭包。
让我们假设 otherFunction 是这样的:
otherFunction = function(p1, callback){}
然后 callback(123456) 将使 anotherParam = 123456;
关于javascript - 将变量从 out 函数传递到 inner 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20541677/