1. This default binding — function calls alone are not bound to an object

  • Eg1: Ordinary functions are called directly without any object association
  function func() {
    // Window
    console.log(this); 
  }
  func()
Copy the code
  • Eg2: Pass a function as an argument to another function
  function foo() {
    // window
    console.log(this);
  }
  function func(bar) {
    bar()
  }
  func(foo)
Copy the code

2. Implicit binding — called by object

  • Eg1: Call a function from an object
  let obj = {
    name: 'coderwhh'.sayThis: function() {
      // obj
      console.log(this);
    }
  }
  obj.sayThis()
Copy the code
  • Eg2: Implicit loss (this case assigns foo of obj to bar and then calls bar, equivalent to a direct call to a normal function, so this still refers to window)
function foo() {
  // Window
  console.log(this);
}

let obj = {
  name: "coderwhh".foo: foo
}
// Assign foo of obj to bar
var bar = obj.foo;
bar();
Copy the code

3. Display the binding

    1. Call, apply implementation
function func() {
  // coderwhh
  console.log(this.name);
}
let obj = {name: 'coderwhh'}
func.call(obj)
func.apply(obj)
Copy the code
    1. The bind to realize
function func() {
  // coderwhh
  console.log(this.name);
}
let obj = {name: 'coderwhh'}
func.bind(obj)()
Copy the code

** Call, apply, bind: ** The first argument passed is the object to be bound. If null or undefined is passed, the display is ignored

    1. Built-in function

(1) setTimeout: setTimeout will pass a function, in which this is usually window

setTimeout(function({
  // window
  console.log(this); 
}, 1000);
Copy the code

(2) Array forEach

    1. The new binding
function Super(name, age) {
  // Super {}
  console.log(this);
  this.name = name
  this.age = age
}
let son = new Super('coderwhh'.18)
Copy the code

Priority: New > Show Binding > Implicit Binding > Default binding

4.ES6 arrow function

The arrow function does not have its own this, and by default points to the host object at which it was defined

let obj = {
  name: 'coderwhh'.sayThis: function() {
    // {name: "coderwhh", sayThis: ƒ}
    console.log(this);
    setTimeout(() = > {
      // {name: "coderwhh", sayThis: ƒ}
      console.log(this);
    }, 1000)
    setTimeout(function () {
      // Window
      console.log(this);
    }, 1000)
  }
}
obj.sayThis()
Copy the code

Reference: front-end interview thoroughly understand this point