对不少前端开发者来讲,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)
}
}
复制代码
题目的参考答案在文末,但我不建议你直接查看答案,而是先阅读并思考文章的中的知识点。app
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
函数
new
出来的实例(例子中的person
)var Person = function () {
this.name = 'linlif'
this.fn = function () {
console.log('fn', this) // {name: "linlif", fn: ƒ}
}
}
var person = new Person()
person.fn()
复制代码
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
post
全局上下文环境,this指向浏览器的window
对象,例如:测试
// 全局的this
console.log(this) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
console.log(this === window) // true
// 全局的普通函数
var global = function () {
console.log(this) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
}
global()
复制代码
使用call()
方法后,this
指向call()
方法的参数。使用apply()
的结果和call()
是一致的,这里不作赘述。关于call()
和apply()
用法的区别,请自行查询相关资料。ui
// 改变调用对象为gObj
var gObj = {
name: 'gName'
}
var aaa = function () {
console.log(this) // {name: "gName"}
console.log(this.name) // gName
}
aaa.call(gObj)
// 改变调用对象为window
var name = 'global'
var bbb = function () {
console.log(this) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
console.log(this.name) // global
}
bbb.call(this)
复制代码
总结:这就是一些关于this的指向问题的我的理解了,若是发现不妥之处,欢迎在评论区指出,或者私信我。this
彩蛋 开篇测试题的参考答案,仅供参考!(有意思的地方:题目中,函数名的第一个字母大写,已经暗示这是一个构造函数)spa
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)
}
}
let obj = new Obj('msg')
obj.waitAndShout()
复制代码
本篇完。code