簡體   English   中英

ES6:將函數應用為類方法

[英]ES6: Applying function as class method

我正在將一個項目從CoffeeScript遷移到ES6(使用6to5和Browserify),並且可能遇到限制,或者我只是不知道正確的語法。 在CoffeeScript中,我可以這樣做:

class SomeView extends BaseView
    triggerMethod: Marionette.triggerMethod

我如何在ES6課程中表達這一點? 我嘗試了幾件事,但無論我嘗試什么,它都會拋出Unexpected token錯誤。 這例如:

let { triggerMethod } = Marionette;

class SomeView extends BaseView {
    triggerMethod, // doesn't work
    triggerMethod: Marionette.triggerMethod // doesn't work
}

現在我可以通過在構造函數中設置它來實現這一點( this.triggerMethod = Marionette.triggerMethod ),但對我來說感覺有點難看(我猜的只是編碼風格的偏好)。 任何幫助,將不勝感激。

您不能在ES6類中聲明屬性,只能聲明方法和靜態方法(請參閱此處了解類聲明的語法,注意ClassElement )。 因此,以下任何示例都是錯誤的:

class A {
    method1: B.someMethod  // wrong!
    method2: function() {} // wrong!
    method3: () => {}      // wrong!
}

您有幾種變體可以解決您的問題:

  1. 使用getter:

     class SomeView extends BaseView { get triggerMethod() { return Marionette.triggerMethod } } 
  2. 呼叫Marionette.triggerMethodtriggerMethodSomeView類:

     class SomeView extends BaseView { triggerMethod() { Marionette.triggerMethod.apply(this, arguments); } } 
  3. 在類聲明SomeView添加到triggerMethod的原型:

     class SomeView extends BaseView { //.. some class declaration } SomeView.prototype.triggerMethod = Marionette.triggerMethod; 

    或者使用Object.assign

     class SomeView extends BaseView { //.. some class declaration } Object.assign(SomeView.prototype, { triggerMethod: Marionette.triggerMethod // ... some another methods }); 
  4. 你已經做了什么 - 將Marionette.triggerMethod添加this 但是你必須意識到,在這種情況下, triggerMethod將保存在對象本身中,而不是原型中。 例:

     class SomeView extends BaseView { constructor() { this.triggerMethod = Marionette.triggerMethod // ... } } 

這就是你所能做的一切。 我認為第一和第二種變體是您的最佳選擇,但這是一個品味問題。

如果我做對了你就可以用這種方式定義類方法:

class SomeView extends BaseView {
    triggerMethod(){
      Marionette.triggerMethod; 
   }
}

與coffeeScript幾乎相同,但需要一些大括號。 我沒試過,但請參閱http://wiki.ecmascript.org/doku.php?id=harmony:classes

暫無
暫無

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

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