Basics of JS scope execution context, this, closure

Preface: JS scope, execution context, this, the closure is a common theme, also a novice relatively ignorant of the knowledge points. Of course, even if you, as a veteran, it may not really be able to understand these concepts thoroughly.

First, the execution context and scope

Scope:

js The scope is lexical scope, namely the function declaration determines the position is located. Lexical scoping refers to the compilation stage produced a set of access rules function identifier. (Different from the lexical scope and dynamic scope is confirmed when the function performed, not js dynamic scope, but the js thislike dynamic scope, will be mentioned later. The concept is very important lexical scope, please be remember and understand.) After all js scope just a "disk space", which is not real variables, but it defines the rules for how the variable access.

The scope chain is essentially a pointer to a list of variable objects, it only references the variable does not contain the actual objects, is the extension of the scope of application of the concept. Scope chain defines a variable set of rules when the current context of how research can not access along the scope chain.

Execution Context:

Execution context refers to the variable object generated when the function is called, this variable we can not directly access the object, but you can visit one of the variables, thisobjects and so on. E.g:

fn the let, bar; // . 1, into the global context 
bar = function (X) { 
  the let B =. 5 ; 
  fn (X + B); // . 3, into the context function fn 
}; 
fn = function (Y) { 
  C the let =. 5 ; 
  the console.log (Y + C); // . 4, Fn the stack, the stack bar 
}; 
bar ( 10); // 2, into the context function bar

Each time the function is called, will have a new execution context, JavaScript engine in a stack way to deal with them, this stack, which we call the call stack (call stack) is function. Bottom of the stack is always the global context, and the stack is the currently active context is being executed, also called active objects (running execution context, the blocks shown in blue), and the difference is suspended underneath context (variable Object).

Summary: scope when the function is declared on a set of variables determining the access rules, and execution context is a series of environment variables when the function executes produced. That scope is defined access rule execution context variables, execution contexts variable lookup In this context scoping rules, and other specific function reference operations.

Summary: scope when the function is declared on a set of variables determining the access rules, and execution context is a series of environment variables when the function executes produced. That scope is defined access rule execution context variables, execution contexts variable lookup In this context scoping rules, and other specific function reference operations.

Understand the process of execution of the function

During the execution of the function is divided into two parts, one part for generating an execution context, this determined point, and generating a variable declaration scope chain; the other part is sequentially performed line by line of code.

:( execution context establishment phase occurs when the function is called before the code is executed && function in vivo)

  1. Generate a variable object , in this order: create the arguments object -> Create function function declarations -> Create var variable declaration
  2. Generate scope chain
  3. Determine this point

Function implementation phase:

  1. Code line by line, this phase will complete variable assignments, function references, as well as execute other code.

Two, this point

Js about the thiskeywords I remember the first contact with the front or in six months or a year to do when (ha ha I was so water). At that time Xu brother (java Gangster) taught me to bind clickwhen the event is thispassed to the event handler, similar <button onclick="handle(this)">确认</button>, I was ignorant, thiswhat the hell? ! Since then, I officially opened the three-year js painful journey: packaging, ah, ah closures, object-oriented, ah, ah, etc., etc. inheritance. thisDespite all the rhetoric of fact, only four points:

Fn = the let function () { 
  Alert ( the this .name) 
} 
the let obj = { 
  name: '' , 
  Fn 
} 
Fn () // method. 1 
obj.fn () // Method 2 
fn.call (obj) // Method . 3 
the let instance = new new Fn () // method 4
  1. Method 1 direct call function fn(), this looked like invocation without an army, the thispoint window(strict mode undefined).
  2. 2-point method is invoked obj.fn(), at this time thispoint to objthe object. Point call thisrefers to a point in front of the object.
  3. 3. The method of using the callfunction to fnthe thispoints of the first parameter, here obj. That use call, apply, bindthe function may be a function of the thisvariable to point to the first parameter.
  4. The method used newto instantiate an object instance, when fnthe thispoints to the examples instance.

If multiple rules simultaneously how to do? In fact, the priority of four rules above is increasing:

fn() < obj.fn() < fn.call(obj) < new fn()

First of all, newthe highest priority calls, as long as newkeyword, thiswill point to the instance itself; then if there is no newkey, there is call、apply、binda function, then thisit points to the first parameter; and if not new、call、apply、bind, only obj.foo()this point is called, thispointing to the previous point the objects; and finally Guanggansiling foo()called in a way, thisto point window(strict mode undefined).

es6 added a function of the arrow, the arrow and the most important feature of a function that is not their own this、arguments、super、new.target, and no arrow function prototype object prototypecan not be used as a constructor ( newan arrow function will complain). It did not have this, so the function of the arrow thisactually refers to a function included in thethis . Whether point calls, or callcalls, you can not change the function of the arrow this.

Third, closures

js closure novice nightmare, in the first three years of school js, I reviewed countless Bowen, hard search concept closures, but in the end nothing. On this definition MDN closure: the closure is a function of a combination of lexical environment and the function declaration.

what? Who speaks to him?

For a long time I have stayed at the closures on such superficial understanding "defined functions in an internal function." This is in fact a necessary condition for closure is formed. Until then looked kyle Gangster "You do not know JAVASCRIPT" book on the definition of closure, I suddenly see the light:

When the function is able to remember where and when access lexical scope, it creates a closure.

let single = (function(){
  let count = 0
  return {
    plus(){
      count++
      return count
    },
    minus(){
      count--
      return count
    }
  }
})()
single.plus() // 1
single.minus() // 0

 

This embodiment is a single model, the model returns an object and assigned to the variable single, the variable singlecontains two functions plusand minus, while these two functions are used where the variable of lexical scope count. Under normal circumstances countand where the execution context will be destroyed at the end of the function execution, but due to countstill being used external environment, so at the end of the function execution countexecution and where the context will not be destroyed, which resulted in the closure. Each call single.plus()or single.minus()will of the closure of countthe variables to be modified, these two functions to hold a reference to where the lexical scope.

In fact, the closure is a special function that can access variables inside a function, but also allows values ​​of these variables remain in memory, garbage collection will not be cleared after the function call.

See a classic case:

// 方法1
for (var i = 1; i <= 5; i++) {
  setTimeout(function() {
    console.log(i)
  }, 1000)
}
// 方法2
for (let i = 1; i <= 5; i++) {
  setTimeout(function() {
    console.log(i)
  }, 1000)
}

Method 1, five cycle timer is set, after one second timer callback function to be performed, print variable ivalues. Needless to say, a second later ihas been incremented to five, so five times the printing timer 5. (Timer and did not find the current variable scope i, so finding a global scope in the scope chain i)

Method 2, since the es6 letwill create local scope, so the loop is set up five scope, and five variable scope of idistribution is 1-5, each scope and set a timer, a print after the second variable ivalue. After a second, variable timer from each parent scope are found iis 1-5. This is a new method of using the abnormality occurs in the variable loop closure solution.

At last

I really learned no more.

 


Author: M & M Seoul, according to
the link: https: //juejin.im/post/5cf8612df265da1bcb4f1bf8
Source: Nuggets
copyright reserved by the authors. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

 

Guess you like

Origin www.cnblogs.com/ning123/p/11329698.html
Recommended