Home > database >  The execution context and closures
The execution context and closures

Time:09-29

###执行上下文 - 先进后出,后进先出, #####函数的执行上下文的生命周期 执行上下文的生命周期分为两个阶段: 1. 创建阶段(进入执行上下文):函数被调用时,进入函数环境,为其创建一个函数上下文 2. 执行阶段(代码执行):执行函数中代码时,此时执行上下文进入执行状态, #####创建阶段的操作 1. 创建变量对象 - 函数环境会初始化创建 Arguments 对象,形式参数(并赋值), - 普通函数声明(并赋值) - 局部变量声明,函数表达式声明(未赋值) 2. 初始化作用域链 3. 确定this指向(this由调用者确定) 4. 确定作用域(词法环境决定,哪里声明定义,就在哪里确定) #####执行阶段的操作 1. 变量对象赋值 - 变量赋值 - 函数表达式赋值 2. 调用函数 3. 按顺序执行其他代码 #####执行上下文与作用域区别 作用域和执行上下文不是同一个概念, 执行全局代码时,会产生一个执行上下文环境,每次调用函数都会执行上下文环境,当函数调用完时,这个上下文环境以及其中的数据都会被消除(除了闭包),处于活动状态的执行上下文环境只有一个 而作用域在函数定义时就已经确定了,不是在函数调用时确定(区别于执行上下文环境,当然this也是上下文环境里的成分) ```JavaScript//全局作用域 let x=100; The function bar () {the console. The log (x); }//fn scope function fn () {let x=50;//bar scope bar (); } fn ();//100 ` ` ` scope is just a "territory", there is no variable, the variable well through corresponding execution context environment variables in the object scope, so * * scope is a static concept, and on the execution context is a dynamic, the two are not the same, * * # # # # variable execution context has become an abstract object, a property, respectively is * * variable object, scope chain and this point to * *, - variable object have contents 1. 2. The Arguments object form parameters, check the context function declarations (3) find a function declaration - just under the variableObject create an attribute using the function name, attribute values is address of the function in the memory of a reference, 4. Determine the current in the context of a local variable, if you meet and the names of the variables with the same name, will ignore the variable - through the example to demonstrate the function of the two stage and how to change the variable object is ` ` ` javascript const foo=function (I) {var a="Hello"; Var b=function privateB () {}; The function c () {}} foo (10);//first in setting up stage fooExecutionContext={variavleObject: {the arguments: {0, 10, length: 1},//determine the arguments object I: 10,//form parameters c: pointer to the function c (),//determine the function of reference a: undefined, initial value is undefined b//local variables: initial value is undefined undefined//local variables}, scopeChain: {}, this: {}} ` ` `

  • Related