Javascript:何时创建范围链? [英] Javascript: when does the scope chain created?

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

问题描述

我听到两种说法:

定义函数时:


  • >第7章:函数表达式闭包部分中< Web开发人员专业JavaScript,第3版>




定义compare()时,其作用域链是
created strong>,预载全局变量对象,并保存到内部[[Scope]]属性中。
当调用该函数时,会创建一个执行上下文,并且其作用域链由
复制函数[[Scope]]属性中的对象构建。


blockquote>

据说范围链是在函数id定义时创建的。



当函数被称为:






现在我们知道每次调用函数时,一个新的执行上下文被创建。然而,在JavaScript解释器中,每个对执行上下文的调用都有两个阶段:




  • 创建阶段[当函数被调用时,但在它执行任何内部代码之前]:

    • 创建变量,函数和参数

    • 创建范围链

    • 确定this的值。
  • >激活/代码执行阶段:

    • 分配值,对函数的引用以及解释/执行代码




    据说范围链是在函数被调用时创建的。



    那么哪个是正确的?

    解决方案

    函数有一个内部的[[Scope]]属性,该函数在中定义时定义



    该范围是范围链的一部分,与当创建新范围时一起该功能被执行。

    I heard two kinds of saying:

    When function is defined:

    • In book Professional Javascript for Web Developers, 3rd Edition, in the Chapter 7: Function Expressions Closures parts:

    When compare() is defined, its scope chain is created, preloaded with the global variable object, and saved to the internal [[Scope]] property. When the function is called, an execution context is created and its scope chain is built up by copying the objects in the function’s [[Scope]] property.

    it's said the scope chain is created when the function id defined.

    When function is called:

    So we now know that everytime a function is called, a new execution context is created. However, inside the JavaScript interpreter, every call to an execution context has 2 stages:

    • Creation Stage [when the function is called, but before it executes any code inside]:
      • Create variables, functions and arguments.
      • Create the Scope Chain.
      • Determine the value of "this".
    • Activation / Code Execution Stage:
      • Assign values, references to functions and interpret / execute code.

    it's said the scope chain is created when the function is called.

    So which is right ?

    解决方案

    Functions have an internal [[Scope]] property which is set to the scope where the function is defined in, when it is defined.

    That scope is then part of the scope chain, together with the new scope created when the function is executed.

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

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