美文网首页
2018-07-14 搬运工:What is the scope

2018-07-14 搬运工:What is the scope

作者: 饥人谷_TIFOSI | 来源:发表于2018-07-14 10:49 被阅读0次

原文地址:https://www.quora.com/What-is-the-scope-chain-in-JavaScript

假设你需要一个小石头完成一个你正在完成的项目。你该怎么办呢?
首先,你现在你自己的房间里找,如果没有找到你将去哪里找呢?
当然是走出房间到你的屋子里找,如果屋子找不到你将去你的院子里找,如果院子里找不到你将去你所在的城市或者国家去找,而这时你找到了这个可以满足你完成项目的石头。
而这和JavaScript有什么关系呢?
这就是作用域链如何在JavaScript(以及许多其他编程语言)中工作的简单类比。因此,假设您是正在执行的代码,它需要变量的值(鹅卵石)来完成其工作。
因此JavaScript引擎将尝试在执行代码的块范围(您的房间)中找到变量的值,当无法在那里找到值时,它将转到其词法外部范围(您的房子),如果甚至没有找到那里,它将到达它的外部范围的外部范围(你的院子),直到它达到全局范围,这就是作用域链。
举个栗子:

function country() { 
    //Let's say global scope
  //pebble found here, will get the value from here 
    var pebble = "stone";
    function city() {
    //pebble not found here too
    //will go to country        
        function colony() {
            //pebble not found here too
       //will go to city            
            function house() {
                //pebble not found here too
        //will go to colony
                function room() {
                    //executing code
                    //pebble not found
                    //will go to house to find it
                    console.log(pebble); //Output "stone"
                }
                room();
            }
            house();
        }
    colony();
    }
  city();
}
country();

这时输出为stone,因为通过一级级查找他终于在country()函数的作用域中找到他想要的变量 pebble;这就是作用域链

相关文章

网友评论

      本文标题:2018-07-14 搬运工:What is the scope

      本文链接:https://www.haomeiwen.com/subject/gkgepftx.html