對很多前端開發者來說,JavaScript語言的this指向是一個令人頭疼的問題。先看下面這道測試題,如果你能實現并解釋原因,那本文對你來說價值不大,可以直接略過。
**開篇測試題:**嘗試實現注釋部分的Javascript代碼,可在其他任何地方添加更多代碼(如不能實現,說明一下不能實現的原因):
let Obj = function (msg) { this.msg = msg this.shout = function () { alert(this.msg) } this.waitAndShout = function () { // 隔5秒后執行上面的shout方面 setTimeout(function () { let self = this return function () { self.shout() } }.call(this), 5000) } }題目的參考答案在文末,但我不建議你直接查看答案,而是先閱讀并思考文章的中的知識點。
一、在對象屬性中的this指向問題
對象的屬性是函數,那么函數中的this指向的是對象本身,即例子中的obj
var obj = { x: 123, fn: function () { console.log(this) // {x: 123, fn: ƒ} console.log(this.x) // 123 } } obj.fn()對象的屬性是函數,函數內部還有函數,那么這個二級(及以上)函數的this指向的是window
var obj = { x: 456, fn: function () { console.log('fn', this) // {x: 456, fn: ƒ} var f1 = function () { console.log('fn.f1', this) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …} console.log(this.x) // undefined var f2 = function () { console.log('fn.f2', this) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …} } f2() } f1() } } obj.fn()從上面的例子,我們可以總結出,對象屬性中,嵌套超過一級及以上的函數,this指向都是window
二、構造函數中的this指向問題
構造函數中的一級函數,this指向通過構造函數new出來的實例(例子中的person)
var Person = function () { this.name = 'linlif' this.fn = function () { console.log('fn', this) // {name: "linlif", fn: ƒ} } } var person = new Person() person.fn()構造函數中的二級(及以上)函數,this指向的是window
var Person = function () { this.name = 'linlif' this.fn = function () { console.log('fn', this) // {name: "linlif", fn: ƒ} var f2 = function () { console.log('f2', this) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …} var f3 = function () { console.log('f3', this) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …} } f3() } f2() } } var person = new Person() person.fn()從上面的例子,我們可以總結出,構造函數中,嵌套超過一級及以上的函數,this指向的都是window
新聞熱點
疑難解答
圖片精選