There are six cases that describe this pointing

1. Call this directly in normal functions

function fun() {
   console.log(this);  // window
   function fn() {
       console.log(this);  // window
   }
   fn();
}
fun();
Copy the code

In the code above, a direct call to the function would point to the window. Note that in strict mode this would point to undefined

2. Call this in the object

let obj = {
   name: 'warmth'.fn() {
     console.log(this);  // {fn: ƒ}
   }
}
obj.fn();
Copy the code

This refers to the object calling the function. This: I refer to whoever called me

3. This in constructors and classes

function Person(name) {
  this.name = name;
  console.log(this);  // Person {name: "warmth "}
}

Person.prototype.playGame = function() {
  console.log(this);  // Person {name: "warmth "}
}

let wq = new Person('warmth');
wq.playGame();
Copy the code

The constructor is used with new, and the new keyword points this in the constructor to the instantiation object, so this in the constructor points to the wq instance object

4. Bind this to the event function

<button> Click button </button>const btn = document.querySelector('button');

btn.addEventListener('click'.function() {
  console.log(this);  // btn
});
Copy the code

This refers to the BTN button, which refers to whoever calls it.

5. This in the timer

const btn = document.querySelector('button');

btn.addEventListener('click'.function () {
  setTimeout(function() {
      console.log(this);  // window
  }, 1000);
  setTimeout(() = > console.log(this), 1000);  //
});
Copy the code

This in the first timer points to window because the timer uses the callback as its handler and this in the callback points to window, but why does the second timer point to the BTN button? Since we use the arrow function, let’s look at the arrow function’s this pointer

6. This in the arrow function

var num = 10;

function fn() {
  var num = 20;
  setTimeout(() = > {
      console.log(this.num);  / / 10
  }, 100)
}
fn();
Copy the code

Arrow functions do not have their own this; they inherit this from the parent scope.

The arrow function this inherits fn() ‘s this. Since fn’s normal function this refers to window, the arrow function refers to window, and since the var variable is mounted to the window object, this.num prints 10. Const let = undefined; const let = undefined