Javascript关闭/变量范围问题 - 我知道它工作,但为什么? [英] Javascript closure / variable scope question - I know it works, but why?

查看:71
本文介绍了Javascript关闭/变量范围问题 - 我知道它工作,但为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了JS一段时间,虽然我知道下面的代码工作,我不真正明白为什么它的工作原理。

I've been developing with JS for a while, and while I know that code below works, I don't really understand why it works.

我看到它的方式,我已经在testClosure函数中定义了testString,我期望在testclosure函数完成后变量离开,因为它局部变量。

The way I see it, I've defined testString in testClosure function, and I'm expecting that variable to 'go away' when testClosure function is done, since it's local variable.

然而,当我用一个定时器调用inner函数时,它仍然知道testString变量。为什么?是不是那个变量在五秒钟之前,当testClosure完成执行?内部函数是否引用了testClosure中的所有变量,并且它们保持有效,直到所有内部函数都完成为止。

However, when I call inner function with a timer, it's still aware of testString variable. Why? Isn't that variable gone five seconds ago when testClosure finished executing? Does the inner function get reference to all variables within testClosure, and they stay valid until all inner functions are done?

function testClosure() {
  var testString = 'hai';

  // after 5 seconds, call function below
  window.setTimeout(function() {

    // check if function knows about testString       
    alert(testString);

  }, 5000);         
}

testClosure();


推荐答案

函数特殊形式创建词法作用域。在该范围内创建的任何对象将在其创建时在范围内看到环境(名称与值的绑定)。

The function special form creates lexical scope. Any object created within that scope will see the environment (the binding of names to values) lexically in scope at the time of its creation.

实际上,创建一个函数是只有在JavaScript中创建词汇作用域,这就是为什么你会一直看到这样的扭曲:

Indeed, creating a function is the only way to create lexical scope in JavaScript, which is why you see contortions like this all the time:

return (function() {
    var privateVariable = 'foo';
    return {
        myProp: privateVariable
    };
})();

这篇关于Javascript关闭/变量范围问题 - 我知道它工作,但为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆