您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

JavaScript范围链

JavaScript范围链

要了解作用域链,您必须知道闭包是如何工作的。

当您嵌套函数时,会形成一个闭包,内部函数即使在其父函数已经执行后,也可以引用其外部封装函数中存在的变量。

JavaScript通过遍历范围链(从本地到全局)来解析特定上下文中的标识符。

考虑具有三个嵌套函数的此示例:

var currentScope = 0; // global scope
(function () {
  var currentScope = 1, one = 'scope1';
  alert(currentScope);
  (function () {
    var currentScope = 2, two = 'scope2';
    alert(currentScope);
    (function () {
      var currentScope = 3, three = 'scope3';
      alert(currentScope);
      alert(one + two + three); // climb up the scope chain to get one and two
    }());
  }());
}());
javascript 2022/1/1 18:14:23 有518人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶