Detailed explanation of this pointing problem case in JavaScript

  • 2021-11-13 06:21:23
  • OfStack

Summarize

Global environment window Ordinary function window or undefined The instance constructed by the constructor this in outer scope when arrow function is defined Methods of the object. The object call (), apply (), bind () INTERNATIONAL PARAMETER 1

Global environment

this points to window objects, whether in strict mode or not.


console.log(this === window)  // true

//  Strict model 
'use strict'
console.log(this === window)  // true

Ordinary function

Normal mode this points to an window object

function test() {
  return this === window
}

console.log(test())  // true
Strict model The value of this is undefined

//  Strict model 
'use strict'

function test() {
  return this === undefined
}

console.log(test())  // true

Constructor

Function is used as a constructor, this points to the constructed instance.


function Test() {
  this.number = 1
}

let test1 = new Test()

console.log(test1.number)  // 1

Arrow function

When the function is an arrow function, this points to the this value in the upper level scope at which the function was defined.


let test = () => {
  return this === window
}

console.log(test())  // true

let obj = {
  number: 1
}

function foo() {
  return () => {
    return this.number
  }
}

let test = foo.call(obj)

console.log(test())  // 1

Method of object

Function is used as a method of an object, this points to the object.


let obj = {
  number: 1,
  getNumber() {
    return this.number
  }
}

console.log(obj.getNumber())  // 1

call (), apply (), bind ()

When the function's call (), apply () methods are called, the function's this points to the first parameter passed in. When the function's bind () method is called, the returned this of the new function points to the first parameter passed in.

let obj = {
  number: 1
}

function test(num) {
  return this.number + num
}

console.log(test.call(obj, 1))  // 2

console.log(test.apply(obj, [2]))  // 3

let foo = test.bind(obj, 3)
console.log(foo())  // 4

Related articles: