Javascript: when does the scope chain created?

£可爱£侵袭症+ 提交于 2019-12-10 21:32:21

问题


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:

  • In this article: What is the Execution Context & Stack in JavaScript?:

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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/21128496/javascript-when-does-the-scope-chain-created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!