箭头函数的 this 指向
从 ES6入门 可以了解到
函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象
那这句话如何理解
//如果不特意绑定 this name这个this 就会指向这个方法对应的域里面的this
let o = {
returnDoSth() {
console.log(this)//o 这个对象
return () => {
console.log(this)//o 这个对象
}
}
}
let dosth = o.returnDoSth()
dosth()// o 这个对象
//绑定this后
let o = {
returnDoSth() {
console.log(this)// window
return () => {
console.log(this)// window
}
}
}
let dosth = o.returnDoSth.call(window)
dosth()
//第二个例子
function foo() {
console.log(this)
}
foo.call({
id: 42 });//打印结果: {id: 42}
foo()//打印结果: window
总结: 在箭头函数当中,若没有特意改变(call apply bind等) this 的指向,则this 指向定义时所在域的 this
//阮一峰 ES6 入门例子
function foo() {
return () => {
return () => {
return () => {
console.log('id:', this.id);
};
};
};
}
var f = foo.call({
id: 1});
//这个操作之后 foo()里面的this 就指向了{id:1},
//而所有箭头函数都在这里面定义,
//所以每个箭头函数下的 this 都是指向{id:1}了
var t1 = f.call({
id: 2})()();
var t2 = f().call({
id: 3})();
var t3 = f()().call({
id: 4});
箭头函数固定不可变,在定义之后就算使用call apply bind 来修改 this 也是不可以的(箭头函数的this总是指向定义时候的this)
由于箭头函数的 this 不可变性,所以不适用于定义对象内部的方法,并且里面包含this
需要动态绑定 this 的时候也不推荐使用,比如事件绑定
end
个人浅见,如有错误,欢迎指正