簡體   English   中英

在課程中使用Ecmascript 6箭頭函數作為方法的正確方法是什么?

[英]What is the right way to use Ecmascript 6 arrow functions as methods in classes?

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”意外地指向某些東西時調用的回調除了對象的適當實例。

然而,say2和say3似乎都很尷尬。 say2在構造函數中定義,say3實際上是箭頭函數的包裝器。 我期待一些sytax可以讓我用類似的東西替換say()行

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

但就我所知,你不能做這樣的事情。 所以問題是,使用箭頭函數作為方法是say2或say3合理的方法。 有沒有更好的辦法?

在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() { () => console.log(this.name) }say3() { return () => console.log(this.name) }不同之處在於前者什么都不做並返回undefined ,而后者將返回一個箭頭函數表達式,當調用時,它將打印到控制台。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM