简体   繁体   English

将变量从out函数传递给内部函数

[英]Passing a variable from out function to inner function

In an object literal, in a function definition, I invoke another function and pass it a function definition. 在对象文字中,在函数定义中,我调用另一个函数并将其传递给函数定义。

...

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

otherFunction will receive param1 as is, but it won't receive param2 as is. otherFunction将按原样接收param1,但不会按原样接收param2。

Why? 为什么?

Because the second parameter passed to other function creates it's own closure and param2 is actually a new reference which overrides the outer reference of param2 in definition of check_on. 因为传递给其他函数的第二个参数创建了它自己的闭包,而param2实际上是一个新的引用,它在check_on的定义中覆盖了param2的外部引用。

I think this is correct. 我认为这是正确的。 But more importantly, how do I pass the valur of param2 into the function definition I pass as the second parameters into otherFunction? 但更重要的是,如何将param2的valur传递给我作为第二个参数传递给otherFunction的函数定义?

Thanks 谢谢

Just remove the param2 param,(anotherParam is not necessary, just to illustrate the problem) 只需删除param2参数,(另一个参数不是必需的,只是为了说明问题)

    otherFunction(param1, function(anotherParam) {

        checkJson(param2);
    });

so the function will become a closure for param2. 所以该函数将成为param2的一个闭包。

Lets assume otherFunction is like this: 让我们假设otherFunction是这样的:

 otherFunction = function(p1, callback){}

Then callback(123456) will make the anotherParam = 123456; 然后回调(123456)将使另一个Param = 123456;

It's because when you declare param2 in the second function it creates a new variable with that name inside the second function. 这是因为当您在第二个函数中声明param2 ,它会在第二个函数内创建一个具有该名称的新变量。 Thus closure is broken. 因此关闭被打破了。 Remove the declaration of param2 or rename it to let closure work. 删除param2的声明或重命名它以使闭包工作。

This tutorial helped me understand better how closure works. 教程帮助我更好地理解了闭包的工作原理。

Below is how I've worked this out to help me illustrate Andrew's answer to myself. 以下是我如何帮助我解释安德鲁对自己的回答。 You might find this useful: 您可能会发现这很有用:

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);

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

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