Scenario 1: Direct function call

function thisfunc() {
  console.log(this)
}
var a = 1;
thisfunc();
Copy the code

The function calls this directly to the window

Scenario 2: The function is called by someone else

function thisfunc() { 
  console.log(this)
};
var a = {
  age: 10,
  thisfunc: thisfunc 
};
a.thisfunc();
Copy the code

This refers to the object a that called the function

Scenario 3: When new an instance

function Person(name) { 
  this.name = name; 
  console.log(this);
}
var p = new Person('zhangsan');
Copy the code

This refers to the new object instance P

Scenario 4: Apply, Call, and bind

function getColor(color) { this.color = color; console.log(this); } function Car(name, color) { this.name = name; getColor.call(this, color); Var Car = new Car(' truck ', 'green '); var Car = new Car(' truck ',' green '); // This in Car refers to CarCopy the code

Scenario 5: This in the arrow function

SetTimeout in this

Var a = {age: 10, myfunc: function() {setTimeout(function() {console.log(this); var a = {age: 10, myfunc: function() {setTimeout(function() {console.log(this); }}}, 0); a.myfunc();Copy the code

SetTimeout () is short for window.settimeout (), where this refers to window.

If we want this in setTimeout to point to a, we can

Var a = {age: 10, let this = that; function() { setTimeout(function() { console.log(that.age); }}}, 0); a.myfunc();Copy the code

You can also use an arrow function to make this point to the nearest outer layer of the arrow function that the non-arrow function points to, which is this that myfunc points to.

var a = { age:10, myfunc: function() { setTimeout(()=> { console.log(this.age); }}}, 0); a.myfunc();Copy the code

conclusion

1. For directly called functions, this is window regardless of where the function is placed

2, for the function called by others, by who point out, this is who

3. In the constructor, this in this. XXX = XXX is an instance of the current class

4, Call, apply, this is the first argument. If you bind a call, you need to call it, and if you bind a call, you need to call it. If you bind a call, you need to call it. If you bind a call, you need to call it.

The arrow function does not have its own this. If it does, this of the outer function is the this of the inner arrow function. If not, this is the window.

6. The timing of this is different between ordinary functions and arrow functions. The this of ordinary functions is judged when the function is called, while the arrow function is judged when the function is defined, that is, by the lexical scope of the arrow function definition.