问题
I heard two kinds of saying:
When function is defined:
- In book
Professional Javascript for Web Developers, 3rd Edition, in theChapter 7: Function ExpressionsClosures 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