普通函数实现
function combine() {
let result = [];
for (let i = 0; i < arguments.length; i++) {
result = result.concat(arguments[i]);
}
return result;
}
箭头函数实现
const combine = (...arrays) => [].concat(...arrays);
箭头函数的 this
指向问题及处理方法
this
指向问题:箭头函数没有自己的 this
,它的 this
指向定义时所在的外层作用域的 this
。在上述 combine
箭头函数实现中,由于函数内部没有使用 this
,所以不存在因 this
指向导致的问题。
- 处理方法:如果在箭头函数内部需要使用外层作用域的
this
,可正常使用。若需要改变 this
指向,由于箭头函数不能通过 call
、apply
、bind
改变 this
指向,可在外层普通函数中获取 this
并传递给箭头函数,或者使用 Function.prototype.bind
绑定外层 this
到一个新的普通函数,再在箭头函数中调用该普通函数。