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)文章
Bootstrap 模態(tài)框(Modal)帶參數(shù)傳值實例
模態(tài)框(Modal)是覆蓋在父窗體上的子窗體。下面通過本文給大家介紹Bootstrap 模態(tài)框(Modal)帶參數(shù)傳值實例代碼,需要的朋友參考下吧2017-08-08關(guān)于layui toolbar和template的結(jié)合使用方法
今天小編就為大家分享一篇關(guān)于layui toolbar和template的結(jié)合使用方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09

JavaScript flash復制庫類 Zero Clipboard

JS實現(xiàn)深度優(yōu)先搜索求解兩點間最短路徑