ang*_*ner 3 javascript binding this ecmascript-6
当我尝试将简单的 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))
Run Code Online (Sandbox Code Playgroud)
上面的一切都按预期运行顺利。
但是一旦我开始使用诸如 const 和箭头函数之类的 ES6 特性,就像这样:
const obj = {num: 2}
const addToThis = (a, b, c) => {
return this.num + a + b + c
}
Run Code Online (Sandbox Code Playgroud)
它不再工作并引发错误:无法读取未定义的属性“num”。
有人可以解释为什么this不再起作用吗?
Lambda 函数(箭头函数)不会创建新的函数上下文并使用调用函数的上下文。
所以“this”指的是父上下文。如果没有 'num' 变量,则它是未定义的。
通常它真的很方便,因为大多数时候你使用一个上下文而不是在你创建的每个函数中创建一个新的上下文。在我看来 call/apply/bind 完全令人困惑,而 lambda 函数使它变得不必要。
| 归档时间: |
|
| 查看次数: |
4561 次 |
| 最近记录: |