我想问一下如何解释这个(javascript函数)

时间:2017-09-16 06:43:45

标签: javascript function scope

1 个答案:

答案 0 :(得分:0)

我认为应该是因为词法作用域或静态作用域以及函数作用域。

词法范围表示变量范围取决于在创建函数 b 的情况下创建函数的时间,num的范围是全局的。

function b() {
 console.log(num)//num is scoped to its parent function it was created in
}

function a() {
  var num = 3;//b will not have access to this num since it was not created here
  arguments[0]();
 }
 num = 1;
 a(test)

但是如果它是动态范围,则变量范围基于执行顺序,在这种情况下,num将是调用者的范围 a num。

如果您尝试此代码段,则会正确打印3。

function a(cb) {
  function b() {
   console.log(num)
  }//b is created here so it has access to num
 var num = 3;
 b();
}
num = 1;
a();

您可以阅读静态范围和动态范围in this question,其中更好地解释了静态与动态,功能与块范围。