execution context, this

1. The execution context or execution environment in js: execution context, referred to as EC;

2.

1 console.log(a);//undefined
2 var a=200;
3 fn('lili');
4 function fn(name){
5   age=23;
6   console.log(name,age);//lili 23
7   var age;
8 }

Analyze the execution process of this code: First of all, you need to remember,

In js, there is variable hoisting. Function declarations and variable declarations are always quietly "hoisted" to the top of the method body by the interpreter, so when writing code, we usually declare these variables before the start of each scope, which is also normal JavaScript The parsing steps are easy for us to understand .

So this code can be transformed like this:

// Function promotion takes precedence over variable promotion 
function fn(name){
     var age;
    age=23;
    console.log(name,age);//lili 23
}

there is a;
 
console.log(a); // The variable a is only declared, but not assigned, so it is undefined
 
var a=200 ;
 
fn( 'lili'); // During the execution of the function, the parameter name='lili' is passed in, and it enters the execution domain of fn, and the var age is advanced; and the value is 23

3. Learn more about the execution context:

  • Scope: a <script> or a function;
  • Global: variable definitions, function declarations;
  • Functions: variable definitions, function declarations, this, arguments 

Small tip: distinguish between function declarations and function expressions

1  // function declaration 
2  function fn(){
 3      ...
 4  }
 5  
6  // function expression 
7  var fn = function (){
 8    ...
 9 }

1.this: The value can only be determined at the time of execution, and cannot be determined at the time of definition.

 1 var a={
 2   name:'A',
 3   fn:function(){
 4     console.log(this.name);//undefined
 5   }
 6 };
 7 
 8 a.fn();//A  this===a
 9 a.fn.call({name:'B'});//B  this==={name:'B'}
10 
11 var fn1=a.fn;
12 fn1();//this===window

2. Several use cases of this:

* Execute as a constructor

1 function Foo(){
2   this.name='shangsan';
3 }
4 var f = new Foo();
5 f.name   //"shangsan"

* Execute as object property

1 var obj={
2   name:'A',
3   printName:function(){
4     console.log ( this === obj ); // true
5     console.log(this.name); //A
6   }
7 }
8 obj.printName();

* Execute as normal function

1 function fn(){
2   console.log(this);//this===window
3 }
4 fn();

*call apply bind

1 function fn(name,age){
2   console.log(name);//lisi
3   console.log(this);//{x: 100}
4 }
5 fn.call({x:100},'lisi',30);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325855128&siteId=291194637