在javascript中this的指向一直是前端同事的心頭病,也同時是各面試題的首選,現(xiàn)在我們就來總結(jié)一下js中this的指向。首先需要了解一下幾個概念:
1:全局變量默認(rèn)掛載在window對象下
2:一般情況下this指向它的調(diào)用者
3:es6的箭頭函數(shù)中,this指向創(chuàng)建者,并非調(diào)用者
4:通過call、apply、bind可以改改變this的指向
下面我們具體分析一下
1:在函數(shù)調(diào)用時
?。ǚ菄?yán)格模式)
const func = function () { console.log(this); const func2 = function () { console.log(this); }; func2(); //Window }; func(); //Window?。▏?yán)格模式)
'use strict' const func = function () { console.log(this); const func2 = function () { console.log(this); }; func2(); //undefined }; func(); //undefined結(jié)合第四和第一兩條規(guī)則:func這個函數(shù)是全局的,默認(rèn)掛載在window對象下,this指向它的調(diào)用者即window,所以輸出window對象,但是在嚴(yán)格模式下,this不允許指向全局變量window,所以輸出為undefined(func2在函數(shù)直接調(diào)用時默認(rèn)指向了全局window,其實(shí)這屬于javascript設(shè)計上的缺陷,正確的設(shè)計方式是內(nèi)部函數(shù)的this 應(yīng)該綁定到其外層函數(shù)對應(yīng)的對象上,為了規(guī)避這一設(shè)計缺陷,聰明的 JavaScript 程序員想出了變量替代的方法,約定俗成,該變量一般被命名為 that。這種方式在接下來會講到)。
2:作為對象方法
const user = { userName: '小張', age: 18, selfIntroduction: function () { const str = '我的名字是:' + this.userName + ",年齡是:" + this.age; console.log(str); const loop = function () { console.log('我的名字是:' + this.userName + ",年齡是:" + this.age); }; loop(); //我的名字是:undefined,年齡是:undefined } }; user.selfIntroduction(); //我的名字是:小張,年齡是:18按照咱的第一條規(guī)則,this指向他的調(diào)用者,selfIntroduction()方法的調(diào)用者是user,所以在selfIntroduction()方法內(nèi)部this指向了他的父對象即user,而loop方法輸出的為undefined的原因就是我在上面所說的javascript的設(shè)計缺陷了,在這種情況下,我們通常選擇在selfIntroduction()方法里將this緩存下來。
const user = { userName: '小張', age: 18, selfIntroduction: function () { const str = '我的名字是:' + this.userName + ",年齡是:" + this.age; console.log(str); const that=this; const loop = function () { console.log('我的名字是:' + that.userName + ",年齡是:" + that.age); }; loop(); //我的名字是:小張,年齡是:18 } }; user.selfIntroduction(); //我的名字是:小張,年齡是:18
新聞熱點(diǎn)
疑難解答
圖片精選