词法作用域与静态作用域

JavaScript使用词法作用域(lexial scope):

词法作用域(lexial scope)/静态作用域(static scope)是在书写代码或者说定义时确定的,而动态作用域是在运行时确定的。 词法作用域关注函数在何处声明,而动态作用域关注函数从何处调用,其作用域链是基于运行时的调用栈的。

代码示例:

词法作用域:

function foo() {

    print a;  // 输出 2

}

 

function bar() {

    var a = 3;

扫描二维码关注公众号,回复: 1390940 查看本文章

    foo();

}

 

var a = 2;

bar();

动态作用域:

function foo() {

    print a;  // 输出 3 而不是2

}

 

function bar() {

    var a = 3;

    foo();

}

 

var a = 2;

bar();

猜你喜欢

转载自www.cnblogs.com/eret9616/p/9124620.html