ES6:将函数应用为类方法 [英] ES6: Applying function as class method
问题描述
我正在将一个项目从CoffeeScript迁移到ES6(使用6to5和Browserify),并且遇到可能的限制,或者我只是不知道正确的语法。在CoffeeScript我可以这样做:
I'm migrating a project from CoffeeScript to ES6 (using 6to5 and Browserify), and am running into possibly a limitation or maybe I just don't know the proper syntax. In CoffeeScript I could do this:
class SomeView extends BaseView
triggerMethod: Marionette.triggerMethod
如何在ES6类中表达?我尝试了几个东西,但它抛出意外令牌
错误,无论我试试。例如:
How do I express this in ES6 classes? I tried a couple of things, but it throws Unexpected token
errors no matter what I try. This for example:
let { triggerMethod } = Marionette;
class SomeView extends BaseView {
triggerMethod, // doesn't work
triggerMethod: Marionette.triggerMethod // doesn't work
}
现在我可以通过在构造函数中设置它来实现这个功能( this.triggerMethod = Marionette.triggerMethod
),但对我来说感觉有点丑(只是一个偏好的编码风格我猜)。
Now I can achieve this by setting it in the constructor (this.triggerMethod = Marionette.triggerMethod
), but it feels a bit ugly to me (just a preference in coding style I guess). Any help would be appreciated.
推荐答案
不能在ES6类中声明属性,只能使用方法和静态方法href =https://people.mozilla.org/~jorendorff/es6-draft.html#sec-class-definitions>这里用于类声明的语法,请注意 ClassElement )。因此,以下任何示例都将是错误的:
You can't declare properties in ES6 classes, only methods and static methods (see here for syntax of class declaration, pay attention to ClassElement). So any of the following examples will be wrong:
class A {
method1: B.someMethod // wrong!
method2: function() {} // wrong!
method3: () => {} // wrong!
}
您有多种变体来处理您的问题:
You have several variants to handle your problem:
-
使用getter:
Use getter:
class SomeView extends BaseView {
get triggerMethod() { return Marionette.triggerMethod }
}
从
调用
Marionette.triggerMethod
> SomeView
Call Marionette.triggerMethod
from triggerMethod
of SomeView
class:
class SomeView extends BaseView {
triggerMethod() {
Marionette.triggerMethod.apply(this, arguments);
}
}
添加 triggerMethod $
到类声明后的
SomeView
原型:
class SomeView extends BaseView {
//.. some class declaration
}
SomeView.prototype.triggerMethod = Marionette.triggerMethod;
或 Object.assign
:
or with Object.assign
:
class SomeView extends BaseView {
//.. some class declaration
}
Object.assign(SomeView.prototype, {
triggerMethod: Marionette.triggerMethod
// ... some another methods
});
您已经做了 - 添加 Marionette.triggerMethod
到 this
。但是你必须知道在这种情况下, triggerMethod
将保存在对象本身,而不是它的原型。示例:
What you already did - add Marionette.triggerMethod
to the this
. But you must be aware that in that case triggerMethod
will be kept in the object itself, not in its prototype. Example:
class SomeView extends BaseView {
constructor() {
this.triggerMethod = Marionette.triggerMethod
// ...
}
}
b
$ b
这就是你能做的。我认为第一和第二个变种是你的最佳选择,但它是一个味道的问题。
That's all you can do. I think the first and second variants are the best choices for your case, but it's a matter of taste.
这篇关于ES6:将函数应用为类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!