??總結(jié)
- 全局環(huán)境 ?? window
- 普通函數(shù) ?? window 或 undefined
- 構(gòu)造函數(shù) ?? 構(gòu)造出來的實例
- 箭頭函數(shù) ?? 定義時外層作用域中的 this
- 對象的方法 ?? 該對象
- call()、apply()、bind() ?? 第一個參數(shù)
全局環(huán)境
無論是否在嚴(yán)格模式下,this 均指向 window
對象。
console.log(this === window) // true
// 嚴(yán)格模式
'use strict'
console.log(this === window) // true
普通函數(shù)
-
正常模式
- this 指向
window
對象
function test() { return this === window } console.log(test()) // true
- this 指向
-
嚴(yán)格模式
- this 值為
undefined
// 嚴(yán)格模式 'use strict' function test() { return this === undefined } console.log(test()) // true
- this 值為
構(gòu)造函數(shù)
函數(shù)作為構(gòu)造函數(shù)使用時,this 指向構(gòu)造出來的實例。
function Test() {
this.number = 1
}
let test1 = new Test()
console.log(test1.number) // 1
箭頭函數(shù)
函數(shù)為箭頭函數(shù)時,this 指向函數(shù)定義時上一層作用域中的 this 值。
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
對象的方法
函數(shù)作為對象的方法使用時,this 指向該對象。
let obj = {
number: 1,
getNumber() {
return this.number
}
}
console.log(obj.getNumber()) // 1
call()、apply()、bind()
- 調(diào)用函數(shù)的 call()、apply() 方法時,該函數(shù)的 this 均指向傳入的第一個參數(shù)。
- 調(diào)用函數(shù)的 bind() 方法時,返回的新函數(shù)的 this 指向傳入的第一個參數(shù)。
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