javascript - ES6 : Applying function as class method

标签 javascript class syntax ecmascript-6

我正在将一个项目从 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 类中声明属性,只能声明方法和静态方法(参见 here 类声明语法,注意 ClassElement)。所以下面的任何一个例子都是错误的:

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

您有多种变体来处理您的问题:

  1. 使用 setter/getter :

    class SomeView extends BaseView {
        get triggerMethod() { return Marionette.triggerMethod }
    }
    
  2. SomeView 类的 triggerMethod 调用 Marionette.triggerMethod:

    class SomeView extends BaseView {
        triggerMethod() { 
            Marionette.triggerMethod.apply(this, arguments);
        }
    }
    
  3. SomeView类声明后的原型(prototype)中添加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 将保存在对象本身中,而不是其原型(prototype)中。示例:

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

这就是你所能做的。我认为第一个和第二个变体是您案例的最佳选择,但这是个人喜好问题。

关于javascript - ES6 : Applying function as class method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28189931/

相关文章:

javascript - 混合每个 Underscore 方法作为 Collection#models 的代理

javascript - Material UI 抽屉中的按钮导航

java - 我类(class)的数据为空?

kotlin - 两个值之间不同值 '===' 的运算符 'name' 的不同结果

ruby - Ruby 中括号内的空格有多重要?

mysql - ON 语句中的别名是未知列

javascript - 从 sessionStorage 读取并使用 jquery 发送到 php 时删除引号

javascript - 如何测试像 modernizr.js 这样的 css 属性

C# 使用命名空间

c++ - 链接器未看到我的 Class.cpp