1. 程式人生 > 程式設計 >JavaScript 中this指向問題案例詳解

JavaScript 中this指向問題案例詳解

總結

  • 全域性環境 ➡️ window
  • 普通函式 ➡️ window 或 undefined
  • 建構函式 ➡️ 構造出來的例項
  • 箭頭函式 ➡️ 定義時外層作用域中的 this
  • 物件的方法 ➡️ 該物件
  • call()、apply()、bind() ➡️ 第一個引數

全域性環境

無論是否在嚴格模式下,this 均指向 window 物件。

console.log(this === window)  // true
// 嚴格模式
'use strict'
console.log(this === window)  // true

普通函式

  1. 正常模式
      lilShTv
    • this 指向 window 物件
    • function test() {
        return this === window
      }
      
      console.log(test())  // true
      
  2. 嚴格模式
    • this 值為 undefined
    • // 嚴格模式
      'use strict'
      
      function test() {
        return this === undefined
      }
      
      console.log(test())  // true
      

建構函式

函式作為建構函式使用時,this 指向構造出來的例項。

function Test() {
  this.number = 1
}

let test1 = new Test()

console.log(test1.number)  // 1

箭頭函式

函式為箭頭函式時,this 指向函式定義時上一層作用lilShTv域中的 this 值。

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

console.log(testlilShTv())  // true
let obj = {
  number: 1
}

function foo()
{ return () => { return this.number } } let test = foo.call(obj) console.log(test()) // 1

物件的方法

函式作為物件的方法使用時,this 指向該物件。

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

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

call()、apply()、bind()

  • 呼叫函式的 call()、apply() 方法時,該函式的 this 均指向傳入的第一個引數。
  • 呼叫函式的 bind() 方法時,http://www.cppcns.com返回的新函式的 this 指向傳入的第一個引數。
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

到此這篇關於 中this指向問題案例詳解的文章就介紹到這了,更多相關Script 中this指向問題內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!