Javascript中的范围链 [英] Scope Chain in Javascript

查看:124
本文介绍了Javascript中的范围链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Javascript中阅读范围链但它对我没有任何意义,任何人都可以告诉我什么是范围链以及它如何与图形或甚至白痴能够理解的东西一起工作。我用谷歌搜索了但我没有找到可以理解的东西:(

I've reading scope chain in Javascript but it didn't make any sense to me, could any one tell me what is scope chain and how it works with a graphic or something even an idiot can understand. I googled it but I didn't find something comprehensible :(

提前致谢。

推荐答案

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

To understand the scope chain you must know how closures work.

嵌套函数时形成闭包,内部函数可以引用变量即使在其父函数已经执行之后,它们也会出现在它们的外部封闭函数中。

A closure is formed when you nest functions, inner functions can refer to the variables present in their outer enclosing functions even after their parent functions have already executed.

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

JavaScript resolves identifiers within a particular context by traversing up the scope chain, moving from locally to globally.

考虑这个带有三个嵌套函数的例子:

Consider this example with three nested functions:

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 Closures
  • Closures

这篇关于Javascript中的范围链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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