JavaScript 中this指向問題案例詳解
更新時間:2021年08月30日 15:18:33 作者:奕玄
這篇文章主要介紹了JavaScript 中this指向問題案例詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下
總結
- 全局環(huán)境 ➡️ window
- 普通函數 ➡️ window 或 undefined
- 構造函數 ➡️ 構造出來的實例
- 箭頭函數 ➡️ 定義時外層作用域中的 this
- 對象的方法 ➡️ 該對象
- call()、apply()、bind() ➡️ 第一個參數
全局環(huán)境
無論是否在嚴格模式下,this 均指向 window 對象。
console.log(this === window) // true
// 嚴格模式 'use strict' console.log(this === window) // true
普通函數
- 正常模式
- this 指向 window 對象
function test() { return this === window } console.log(test()) // true - this 指向 window 對象
- 嚴格模式
- this 值為 undefined
// 嚴格模式 'use strict' function test() { return this === undefined } console.log(test()) // true - this 值為 undefined
構造函數
函數作為構造函數使用時,this 指向構造出來的實例。
function Test() {
this.number = 1
}
let test1 = new Test()
console.log(test1.number) // 1
箭頭函數
函數為箭頭函數時,this 指向函數定義時上一層作用域中的 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
對象的方法
函數作為對象的方法使用時,this 指向該對象。
let obj = {
number: 1,
getNumber() {
return this.number
}
}
console.log(obj.getNumber()) // 1
call()、apply()、bind()
- 調用函數的 call()、apply() 方法時,該函數的 this 均指向傳入的第一個參數。
- 調用函數的 bind() 方法時,返回的新函數的 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
到此這篇關于JavaScript 中this指向問題案例詳解的文章就介紹到這了,更多相關JavaScript 中this指向問題內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
javascript 實現簡單的table排序及table操作練習
在這個列子中,練習了table的操作,主要有:tBodies、rows、cells,還有有關數組的排序方法:sort,按興趣的朋友可以研究下2012-12-12
多選列表框動態(tài)添加,移動,刪除,全選等操作的簡單實例
本篇文章主要是對多選列表框動態(tài)添加,移動,刪除,全選等操作的簡單實例進行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01

