3

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 处理,并且应该能够将它们传递给单击处理程序和其他需要回调的函数,而不必担心在某些情况下会调用回调,这会导致“this”意外指向某些东西除了对象的适当实例。

尽管如此,say2 和 say3 都显得很尴尬。say2 在构造函数中定义,而 say3 实际上是箭头函数的包装器。我期待一些语法,它可以让我用类似的东西替换 say() 行

say: () => console.log(this.name)

但据我所知,你不能做这样的事情。所以问题是,使用箭头函数作为方法是say2或say3的方法是合理的。有没有更好的办法?

4

1 回答 1

2

在 ES6 语法中,类的主体可能只包含方法定义,因此此处不允许使用箭头函数表达式。这是语法相关部分的简化片段:

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传递它时绕过它,如element.addEventListener('click', this.say.bind(this));.
  • say2会起作用,但是你失去了在构造函数之外指定方法的便利。
  • say3不起作用 - 虽然它在语法上是有效的,但它会被解析为一个方法,它的主体由一个箭头函数组成。澄清一下,say3() { () => console.log(this.name) }区别say3() { return () => console.log(this.name) }在于前者什么都不做并返回undefined,而后者将返回一个箭头函数表达式,当被调用时,它将打印到控制台。
于 2015-01-30T17:24:01.117 回答