作者太久没学习了,脑子都快废了,很多都忘记了。
本文只记录个人学习记录,若有错误请指出,大佬勿喷。
总结
箭头函数的提出:确保this的指向正确,不被外部影响。
特殊点
1. 箭头函数内的this指向?
箭头函数内的this指向:始终指向定义时所在的对象,而不是运行时所在的对象。
如何理解定义和运行?
function foo_putong() {
setTimeout(function(){
console.log('id:', this.id); //普通函数
}, 100);
}
function foo_jiantou() {
setTimeout(() => {
console.log('id:', this.id); //箭头函数
}, 100);
}
var id = 21;
foo_putong.call({ id: 42 });// id: 21
foo_jiantou.call({ id: 42 });// id: 42
- 普通函数,输出21,this指向运行时的全局对象(window)。
- 箭头函数,输出42,this指向定义时的所在对象(本例是{id: 42})。
目的:箭头可以让this指向固定化,只取决于定义时,不受运行时的影响。
var handler = {
id: '123456',
init: function() {
document.addEventListener('click',
event => this.doSomething(event.type), false);
},
doSomething: function(type) {
console.log('Handling ' + type + ' for ' + this.id);
}
};
init中的this指向:
- 普通函数,报错,this指向运行时的对象(document对象)。
- 箭头函数,正常,this指向定义时的对象(handler对象)。
2. 箭头函数内的this有无?
箭头函数内没有自己的this,而是引用外层的this。
function foo() {
return () => {
return () => {
return () => {
console.log('id:', this.id);
};
};
};
}
var f = foo.call({id: 1});
var t1 = f.call({id: 2})()(); // id: 1
var t2 = f().call({id: 3})(); // id: 1
var t3 = f()().call({id: 4}); // id: 1
foo内的箭头函数都没有自己的this,始终指向外层的this。
所以,始终指向定义时的对象,这里是{id:1}。
3. 不能用call、apply、bind?
由于箭头函数没有自己的this,所以不能用call()、apply()、bind()这些方法去改变this的指向。
(function() {
return [
(() => this.x).bind({ x: 'inner' })()
];
}).call({ x: 'outer' });
// ['outer']
4. 不能用arguments、super、new.target?
function foo() {
setTimeout(() => {
console.log('args:', arguments);
}, 100);
}
foo(2, 4, 6, 8)
// args: [2, 4, 6, 8]
箭头函数内,变量arguments,其实是函数foo的arguments变量。
作者:阮一峰
链接:es6.ruanyifeng.com/?search=imp…
来源:es6.ruanyifeng.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。