对很多前端开发者来说,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
新闻热点
疑难解答
图片精选