JavaScript 中this指向問題案例詳解
總結(jié)
- 全局環(huán)境 ➡️ window
- 普通函數(shù) ➡️ window 或 undefined
- 構(gòu)造函數(shù) ➡️ 構(gòu)造出來的實例
- 箭頭函數(shù) ➡️ 定義時外層作用域中的 this
- 對象的方法 ➡️ 該對象
- call()、apply()、bind() ➡️ 第一個參數(shù)
全局環(huán)境
無論是否在嚴格模式下,this 均指向 window 對象。
console.log(this === window) // true
// 嚴格模式 'use strict' console.log(this === window) // true
普通函數(shù)
- 正常模式
- 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
構(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
到此這篇關(guān)于JavaScript 中this指向問題案例詳解的文章就介紹到這了,更多相關(guān)JavaScript 中this指向問題內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript 實現(xiàn)簡單的table排序及table操作練習(xí)
在這個列子中,練習(xí)了table的操作,主要有:tBodies、rows、cells,還有有關(guān)數(shù)組的排序方法:sort,按興趣的朋友可以研究下2012-12-12
前端實現(xiàn)(excel)xlsx文件預(yù)覽的詳細步驟
excel的預(yù)覽庫有不少,也都很強大,但是能很簡單實現(xiàn),下面這篇文章主要給大家介紹了關(guān)于前端實現(xiàn)(excel)xlsx文件預(yù)覽的詳細步驟,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-03-03
JS實現(xiàn)兩表格里數(shù)據(jù)來回轉(zhuǎn)移的方法
這篇文章主要介紹了JS實現(xiàn)兩表格里數(shù)據(jù)來回轉(zhuǎn)移的方法,涉及javascript鼠標事件及頁面元素的相關(guān)操作技巧,需要的朋友可以參考下2015-05-05
javascript實現(xiàn)圖片跟隨鼠標移動效果的方法
這篇文章主要介紹了javascript實現(xiàn)圖片跟隨鼠標移動效果的方法,涉及javascript鼠標事件及頁面元素的相關(guān)操作技巧,需要的朋友可以參考下2015-05-05
javascript手風(fēng)琴下拉菜單實現(xiàn)代碼
手風(fēng)琴效果的下拉菜單大家都有見到過吧,實現(xiàn)的方法也有很多,這篇文章就為大家分享了javascript手風(fēng)琴下拉菜單實現(xiàn)代碼,純手寫的,感興趣的朋友不要錯過。2015-11-11
多選列表框動態(tài)添加,移動,刪除,全選等操作的簡單實例
本篇文章主要是對多選列表框動態(tài)添加,移動,刪除,全選等操作的簡單實例進行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01

