this指向不是在创建时指定的,而是由最后调用它的对象决定的。
全局对象的this
在非严格模式下,this指向window;在严格模式下,this指向undefined。
1)简单版
function f1 () {
console.log(this)
}
function f2 () {
'use strict'
console.log(this)
}
f1() // window
f2() // undefined
2)赋值版
const foo = {
bar: 10,
fn: function() {
console.log(this)
console.log(this.bar)
}
}
var fn1 = foo.fn
fn1()
foo.fn在赋值给fn1后,fn1仍然是在window的全局环境下执行的,因此输出
// window
// undefined
其结果与以下语句等价:
console.log(window)
console.log(window.bar)
上下文对象调用中的this
一般通过上下文对象调用函数时,函数体内的this会被绑定到该对象上。
const student = {
name: 'Lucas',
fn: function() {
return this
}
}
console.log(student.fn() === student) // true
当存在更复杂的调用关系时,this会指向最后调用它的对象。
const person = {
name: 'Lucas',
brother: {
name: 'Mike',
fn: function() {
return this.name
}
}
}
console.log(person.brother.fn()) // Mike
箭头函数中的this
箭头函数中的this指向是由其所属函数或全局作用域来决定的。
const foo = {
fn: function() {
setTimeout(function() {
console.log(this)
})
}
}
console.log(foo.fn())
在这段代码中,this出现在setTimeout的匿名函数中,因此this指向window对象。
如果需要让this指向foo这个对象,则可以巧用箭头函数来解决,代码如下:
const foo = {
fn: function() {
setTimeout(() => {
console.log(this)
})
}
}
console.log(foo.fn()) // { fn: f }
除了巧用箭头函数外,
也可以复制当前对象的this指向到一个新的变量(如that)中。【JavaScript】var that = this
最后,看一个综合例子:
const obj = {
fn() {
console.log(this)
const f = () => {
console.log(this)
}
f()
}
}
obj.fn()
const fn = obj.fn
fn()
const f = () => {
这里因为巧用箭头函数,所以this指向是跟fn里的console.log(this)是一样的。
obj.fn()
的最后调动对象是obj,所以this指向obj。
fn()
的最后调用对象是window,所以this指向window
其输出结果如下:
// { fn: f }
// { fn: f }
// window
// window