将变量从外函数传递给内函数

Passing a variable from out function to inner function

本文关键字:函数 变量      更新时间:2024-07-03

在对象文字中,在函数定义中,我调用另一个函数并向其传递函数定义。

...
var myObjLiteral = {
    ...
    , check_on: function(param1, param2) {
           ref.otherFunction(param1, function(param2){checkJson(param2)}); 
    }
}

otherFunction将按原样接收param1,但不会按原样接收param2。

为什么?

因为传递给其他函数的第二个参数创建了它自己的闭包,而param2实际上是一个新的引用,它覆盖了check_on定义中param2的外部引用。

我认为这是正确的。但更重要的是,我如何将param2的值传递到函数定义中,作为传递到otherFunction的第二个参数?

感谢

只需删除param2参数(不需要另一个param,只是为了说明问题)

    otherFunction(param1, function(anotherParam) {
        checkJson(param2);
    });

因此该函数将成为param2的闭包。

假设otherFunction是这样的:

 otherFunction = function(p1, callback){}

然后回调(123456)将使另一个Param=12346;

这是因为当您在第二个函数中声明param2时,它会在第二次函数中创建一个具有该名称的新变量。因此关闭被打破。删除param2的声明或对其进行重命名以使闭包工作。

本教程帮助我更好地理解闭包是如何工作的。

下面是我如何计算出来的,以帮助我向自己说明Andrew的答案。你可能会发现这很有用:

var myObjLiteral = {
  check_on: function (param1, param2) {
    var _this = this;
    this.otherFunction(param1, function () {
        _this.checkJson(param2);
    });
  },
  otherFunction:  function(param1, callback) {
    console.log('otherFunction', param1); // otherFunction 1
    callback();
  },
  checkJson: function (param2) {
    console.log('checkJson', param2); // checkJson 2
  }
}
myObjLiteral.check_on(1, 2);