Ecmascript 6箭头函数似乎非常适合用作类中的方法,因为它们不受调用上下文与“this”引用的干扰。不过,我看不到如何使用它们。以下是一个类,显示了我可以看到的两种使用方式:
class Person {
constructor(aName) {
this.name = aName;
this.say2 = () => console.log(this.name);
}
say() { console.log(this.name) }
say3() { () => consolve.log(this.name) }
}
say2和say3都将使用新的this处理,并且应该能够将它们传递给click处理程序,以及其他需要回调的函数,而不必担心在某些导致“this”意外指向某事的回调中被调用而不是对象的适当实例。
不过,say2和say3都显得很尴尬。 say2是在构造函数中定义的,而say3实际上是箭头功能的包装。我期待一些语法,这样我就可以将say()行替换为类似
say: () => console.log(this.name)
但据我所知,您无法做任何这样的事情。所以问题是,使用箭头函数作为方法是say2或say3的方法是合理的。有没有更好的办法?
最佳答案
在ES6语法中,the body of a class只能由method definitions组成,因此此处不允许使用箭头函数表达式。这是语法相关部分的简化片段:
ClassBody :
ClassElementList
ClassElementList :
ClassElement
ClassElementList ClassElement
ClassElement :
MethodDefinition
static MethodDefinition
;
MethodDefinition :
PropertyName ( StrictFormalParameters ) { FunctionBody }
GeneratorMethod
get PropertyName ( ) { FunctionBody }
set PropertyName ( PropertySetParameterList ) { FunctionBody }
因此,在您的示例中:
class Person {
constructor(aName) {
this.name = aName;
this.say2 = () => console.log(this.name);
}
say() { console.log(this.name) }
say3() { () => console.log(this.name) }
}
say
是一个普通的方法定义,其this
绑定(bind)也遇到与普通函数相同的问题。但是,通过bind
可以解决该问题,就像element.addEventListener('click', this.say.bind(this));
一样。 say2
可以使用,但是您失去了在构造函数之外指定方法的便利。 say3
无效-尽管它在语法上有效,但将被解析为一种方法,其主体由单个箭头函数组成。为了明确起见,say3() { () => console.log(this.name) }
和say3() { return () => console.log(this.name) }
的不同之处在于,前者将不执行任何操作并返回undefined
,而后者将返回箭头函数表达式,该表达式将在调用时打印到控制台。