简体   繁体   English

为什么这种关闭工作?

[英]Why does this closure work?

Say I have a simple function that alerts a message: 假设我有一个简单的函数来警告消息:

function callMessage(msg){
        alert(msg);
    }

Now when I call it like so, it does not work. 现在,当我这样称呼它时,它不起作用。 Throws error "hey is not defined" 引发错误“嘿未定义”

function sayHi(){
        var hey = "hi there"
        setTimeout("callMessage(hey)", 1000);
    }
    sayHi();

But when I call it inside an anonymous function it does work: 但是当我在一个匿名函数中调用它时它确实有效:

function sayHi(){
        var hey = "hi there"
        setTimeout(function(){callMessage(hey);}, 1000);
    }
    sayHi();

Why is the "hey" variable only visible when I put it inside an anonymous function? 为什么“hey”变量只有在我将其放入匿名函数时才可见?

In the first example, the code is evaluated after the timer expired and the current scope was left. 在第一个示例中,在计时器到期并且保留当前范围之后评估代码。 hey is undefined at that moment. hey ,那一刻是不确定的。

The second example - the proper way to use setTimeout - uses an anonymous function created when invoking setTimeout() . 第二个示例 - 使用setTimeout的正确方法 - 使用在调用setTimeout()时创建的匿名函数。 This anonymous function also receives a copy of the current scope. 此匿名函数还接收当前范围的副本。

"callMessage(hey)" is a string, not a closure. “callMessage(嘿)”是一个字符串,而不是一个闭包。 It's evaluated when the timeout runs, and at this point the variable hey isn't in scope. 它在超时运行时进行评估,此时变量hey不在范围内。

it's normal. 这是正常的。

The second example creates what we call a fixture, this is an execution context. 第二个例子创建了我们称之为fixture的东西,这是一个执行上下文。 hey variable variable is saved to be used by the anonymous function in memory. 保存变量变量以供内存中的匿名函数使用。

In your first example, the hey variable is not saved in a fixture (because javascript can't know that you will used the variable after) and so can not be retrieved when the string is evaluated 在你的第一个例子中,hey变量没有保存在fixture中(因为javascript不能知道你之后会使用变量)因此在评估字符串时无法检索

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

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