当我尝试将一个简单的ES5代码转换为ES6时,我有些困惑。
假设我有这段代码:
var obj = {num: 2}
var addToThis = function (a, b, c) {
return this.num + a + b + c
}
// call
console.log(addToThis.call(obj, 1, 2, 3))
// apply
const arr = [1, 2, 3]
console.log(addToThis.apply(obj, arr))
// bind
const bound = addToThis.bind(obj)
console.log(bound(1, 2, 3))
以上所有内容都运行顺利,符合预期。
但是一旦我开始使用ES6功能,比如const和箭头函数,像这样:
const obj = {num: 2}
const addToThis = (a, b, c) => {
return this.num + a + b + c
}
它不再起作用并抛出错误:无法读取未定义属性“num”。
有人能解释一下为什么this
不再起作用吗?