简体   繁体   English

有人可以解释这个javascript闭包是如何工作的吗?

[英]Can someone explain how this javascript closure works?

Ok, I am staring to learn how closures work......and I have been stuck on this one for a few hours. 好的,我正盯着了解闭瓶的工作原理......我已经坚持了几个小时。 I just don't understand how it works. 我只是不明白它是如何工作的。

I have to find the final value for the variable result . 我必须找到变量结果的最终值。

    var hidden = mystery(3);
    var jumble = mystery3(hidden);
    var result = jumble(2);

    function mystery ( input ){
      var secret = 4;
      input+=2;
      function mystery2 ( multiplier ) { 
         multiplier *= input;
         return secret * multiplier;
      }
      return mystery2;
    }


    function mystery3 ( param ){
      function mystery4 ( bonus ){
        return param(6) + bonus;
      }
      return mystery4;
    }

The answer is 122, but I am not sure how that number. 答案是122,但我不确定这个数字是多少。

The answer that I calculated is is 362. That was obviously wrong. 我计算的答案是362.这显然是错误的。

I got 362 like this 我这样得了362

var hidden = mystery(3);
var jumble = mystery3(hidden);
var result = jumble(2);

function mystery ( input ){  //used 3 as an input
  var secret = 4;
  input+=2;
  function mystery2 ( multiplier ) { //used 3 as multiplier
     multiplier *= input; // 3 * 5
     return secret * multiplier;
  }
  return mystery2;   //returned 60
}


function mystery3 ( param ){  //used 60 as param
  function mystery4 ( bonus ){ //used 2 as bonus
    return param(6) + bonus; //60(6) + 2
  }
  return mystery4; // answer is 362
}

Can someone tell me how exactly you can get the answer 122? 有人能告诉我你究竟能得到答案122吗?

In simple words, closure means that a value of a local variable that has gone out of scope is retained inside a function. 简单来说,闭包意味着超出范围的局部变量的值保留在函数内。

Let's look at your code step by step: 让我们一步一步看看你的代码:

var hidden = mystery(3);

Now, mystery returns a function. 现在, mystery回归一个功能。 But what does it actually return. 但它实际上又回归了什么呢。 A simple alert(hidden) statement will tell you that it returns, 一个简单的alert(hidden)语句会告诉你它返回,

function mystery2( multiplier ) {
    multiplier *= input;
    return secret * multiplier;
}

Now if you look at the values of the local variables of this function, 现在,如果你看一下这个函数的局部变量的值,

  • multiplier is an argument, it's value will be whatever that is passed to it when it is called multiplier是一个参数,它的值将是调用它时传递给它的任何值
  • But what is the value of input ? 但是input的价值是什么?
  • And of secret ? secret

This is where closures come into play. 这就是闭包发挥作用的地方。 The value of input will be taken from the scope that this function was created on. 输入的值将取自创建此函数的范围。 What was the values for input and secret when this function was created? 创建此函数时inputsecret的值是多少? Let's take a look at mystery again: 让我们再来看看mystery

function mystery ( input ){ // value 3 is passed here as a parameter
    var secret = 4;
    input+=2;
    ...
}

So we find that input was in fact had the value 5 , and secret had the value 4 . 因此我们发现input实际上具有值5 ,而secret具有值4 Now the returned function essentially becomes equivalent to: 现在返回的函数基本上等同于:

function mystery2( multiplier ) {
    multiplier *= 5;
    return 4 * multiplier;
    // for future use, let's say that above statement is equivalent to:
    // return 4 * (multiplier * 5);                               ----- (1)
    // (now be a good boy/girl and don't scroll down to end)
}

OK, next: 好的,下一个:

var jumble = mystery3(hidden);

Again, mystery3 returns a function. 同样, mystery3返回一个函数。 alert(jumble) gives us this: alert(jumble)给了我们这个:

function mystery4( bonus ){
    return param(6) + bonus;
}

Again, thinking in the same way as before we can say that this is equivalent to: 再次,以与之前相同的方式思考,我们可以说这相当于:

function mystery4( bonus ){
    return mystery2(6) + bonus; // param <- hidden <- mistery2
} //                                                             ----- (2)

And lastly, 最后,

var result = jumble(2);

Which is equivalent to: 这相当于:

var result = mystery4(2);

That is, 那是,

var result = mystery2(6) + 2; // because (2), see above

Which is, 这是,

var result = 4 * (6 * 5) + 2; // because (1), see above

Phew... 呼...

122

I've changed some names around to make it more readable for me, add a few comments to point out values at the time of the line's execution. 我已经更改了一些名称以使其对我更具可读性,添加一些注释以指出行执行时的值。

var mystery2_handle = mystery(3);
var mystery4_handle = mystery3(mystery2_handle);
var result = mystery4_handle(2);

function mystery ( input ){
    var secret = 4;
    input+=2; //5
    function mystery2 ( multiplier ) { 
        multiplier *= input; //6*5
        return secret * multiplier; //30*4
    }
    return mystery2;
}


function mystery3 ( _mystery2_handle ){
    function mystery4 ( bonus ){ //2
        return _mystery2_handle(6) + bonus; //120+2
    }
    return mystery4;
}

Let's go step by step: 让我们一步一步走:

  1. mystery(3) -> input will be set to 5 神秘(3) - >输入将设置为5
  2. then return mystery2 function handle 然后返回mystery2函数句柄
  3. pass that handle to mystery3 将该句柄传递给mystery3
  4. which returns mystery4 handle inside of which the mystery2 handle is accessed 返回访问mystery2句柄的mystery4句柄
  5. execute mystery4 with bonus parameter set to 2 执行myst​​ery4,将参数设置为2
  6. execute mystery2 with multiplier parameter set to 6 执行myst​​ery2,乘数参数设置为6
  7. in which multiplies it by 5 = 30 其中乘以5 = 30
  8. then multiply secret 4 by 30 = 120 然后将秘密乘以4乘以30 = 120
  9. return the 120 to which 2 (bonus) is added in mystery 4 返回在神秘4中添加2(奖励)的120
  10. Voila 122 Voila 122

http://jsfiddle.net/3F4pz/ Run the code insert alerts where needed to check data. http://jsfiddle.net/3F4pz/在需要检查数据的地方运行代码插入警报。 Just remember that even though the code is top down does not mean it's executed that way. 请记住,即使代码是自上而下也不意味着它以这种方式执行。 And I'm not sure how you came up with 362. 而且我不确定你是怎么想出362的。

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

相关问题 有人可以解释这个 JavaScript 代码是如何工作的吗? - Can someone explain how this JavaScript code works? 有人可以解释这个Javascript关闭示例 - Can someone explain this Javascript closure example 有人可以向我解释逻辑“OR”运算符的范围在 Javascript 中是如何工作的吗? - Can someone explain to me how the scope of the logical "OR" operator works in Javascript? 有人可以解释 javascript 排序方法是如何工作的吗? - can someone explain how javascript sort method works? 有人可以解释一下此JavaScript / Angular代码如何工作吗? - Can someone explain how this JavaScript/Angular code works? 有人可以帮助解释 for 循环中的 setTimeout 是如何工作的吗? 这和闭包有关系吗 - Can someone help explain how a setTimeout within a for loop works? Does this have anything to do with closure 有人可以向我解释此JavaScript函数的流程吗? (关闭概念) - Can someone explain me the flow of this JavaScript function? (Closure concept) 有人可以解释一下这个功能是如何工作的吗? - Can someone please explain how this function works? 有人可以向我解释这个功能是如何工作的吗? - Can someone explain to me how this function works? 有人可以详细解释 useEffect 的工作原理吗? - Can someone explain how useEffect works in detail?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM