对箭头函数感到困惑
Confused about arrow functions
你能告诉我片段 1 有什么问题吗? obj.discover() 的预期输出是 3。我如何不能将 this
绑定到对象的箭头函数方法?
'use strict'
// Snippet 1
var obj = {
data: 3,
discover: () => {
return this.data
}
}
obj.discover() // -> undefined
obj.discover.bind(obj)() // undefined
// but if I don't use the arrow notation, everything works
// Snippet 2
var obj2 = {
data: 3,
discover: function(){
return this.data
}
}
obj2.discover() // -> 3
箭头函数不允许绑定。检查 MDN 上的 this 参考资料:
An arrow function expression has a shorter syntax compared to function
expressions and does not bind its own this, arguments, super, or
new.target.
箭头函数会将 this
解析为其词法范围。
箭头函数不仅是语法糖,而且在某些行为上也有所不同。在箭头函数中,this
始终指向它在函数定义时指向的对象。
箭头函数与普通函数不同,不应用作对象方法。它们不绑定 'this',等等。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
你能告诉我片段 1 有什么问题吗? obj.discover() 的预期输出是 3。我如何不能将 this
绑定到对象的箭头函数方法?
'use strict'
// Snippet 1
var obj = {
data: 3,
discover: () => {
return this.data
}
}
obj.discover() // -> undefined
obj.discover.bind(obj)() // undefined
// but if I don't use the arrow notation, everything works
// Snippet 2
var obj2 = {
data: 3,
discover: function(){
return this.data
}
}
obj2.discover() // -> 3
箭头函数不允许绑定。检查 MDN 上的 this 参考资料:
An arrow function expression has a shorter syntax compared to function expressions and does not bind its own this, arguments, super, or new.target.
箭头函数会将 this
解析为其词法范围。
箭头函数不仅是语法糖,而且在某些行为上也有所不同。在箭头函数中,this
始终指向它在函数定义时指向的对象。
箭头函数与普通函数不同,不应用作对象方法。它们不绑定 'this',等等。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions