this指向
this指的是当前函数运行的爹
普通函数被调用/运行时,才会确定this的指向。
箭头函数被定义时,就已经确定了this的指向
第一种:默认
var a = 1
function test () {
console.log(this.a)
}
test() // 1
默认指向全局对象,浏览器是window,node是global。
严格模式下指向undefined
第二种:有爹
var a = 1
function test () {
console.log(this.a)
}
var obj = {
a: 2,
test
}
var obj0 = {
a: 3,
obj
}
obj0.obj.test()
运行时的爹是obj
,因此this指向obj
此外只认直属上级。就好像obj的上级是window一样,只认obj
迷惑1:看起来有爹其实没有
var a = 1
function test () {
console.log(this.a)
}
var obj = {
a: 2,
test
}
var testCopy = obj.test
testCopy() // 1
毕竟把函数体拿出来给了testCopy
了,所以还是在window情况下运行的
迷惑2:settimeout
var a = 1
function test () {
console.log(this.a)
}
var obj = {
a: 2,
test
}
setTimeout(obj.test) // 1 // 不传时间就是0
相当于0时间之后运行obj.test
,爹还是window
第三种:改this指向:call/apply/bind
var a = 1
function test () {
console.log(this.a)
}
var obj = {
a: 2,
test
}
var testCopy = obj.test
testCopy.call(obj) // 2
把obj.test
的this改成了obj
apply跟call的区别只是传参,作用是一样的。
bind有点区别,bind能让我们的函数延迟执行,apply与call调用就执行,所以bind这样的形式我们也称为函数柯里化【foo(3)(4)这种】
第四种:new
var a = 1
function test (a) {
this.a = a
}
var b = new test(2)
console.log(b.a) // 2
test是构造函数,那么this就指向构造后的对象,这里是b
第五种:箭头函数
var a = 1
var test = () => {
console.log(this.a)
}
var obj = {
a: 2,
test
}
obj.test() // 1
Last updated
Was this helpful?