this 的指向
fn(1, 2) 等价于 fn.call(undefined, 1, 2)
obj.fn(1, 2) 等价于 obj.fn.call(obj, 1, 2)
obj.child.fn(1, 2) 等价于 obj.child.fn.call(obj.child, 1, 2)
document.addEventListener('click', function(e){
console.log(this); // 这里 this 指代document对象,原因可能是内部调用时指定了 document 为 this
}, false);
this 是 call 的第一个参数。
this 的值和函数如何被调用有关。
const a = {
f() {
console.log(this)
}
}
a.f() // this 指向 a
const f2 = a.f
f2() // this 指向 Window
const arr = [a.b.f]
arr[0]() // this 指向 arr,因为 JS 中的数组实际是对象,所以等价于 a.f()
箭头函数
因为箭头函数没有自己的 this,所以通过 call 和 apply 的形式调用箭头函数,第一个参数会被忽略。
箭头函数不绑定自己的 this,分析 this 指向时可以将降头函数看成代码块。
const f1 = function() {
return () => console.log(this);
}
const f2 = f1.call({ name: 'wang' })
const f3 = f1()
f2() // 打印出 {name: 'wang'}
f3() // 打印出 Window {...
箭头函数中 this 特性的应用:
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // this 正确地指向 person 对象
}, 1000);
}
var p = new Person();
call 和 apply
call 和 apply 可以动态绑定 this
fn.call( obj, a, b, c )
fn.apply( obj, [a, b, c] )
const obj = {
name: 'hehe'
}
function fn() {
console.log(this.name)
}
fn.call(obj)
bind
bind 会创建一个新函数,新函数中的 this 是 bind 传入的参数
const obj = {
name: 'wang'
}
function fn() {
console.log(this.name)
}
const f2 = fn.bind(obj)
f2()
参考链接:
Understanding "this" in javascript with arrow functions | Codementor
this 的值到底是什么?一次说清楚 - 知乎
网友评论