是否可以在ES2015中导入类方法 [英] Is it possible to import class methods in ES2015
问题描述
导出功能myMethod(){}
在另一个模块中实例化一个类:
code> import {myMethod} from'./methodFile';
class MyClass {
constructor(){}
myMethod // does not work
}
可以使用 myMethod
作为 MyClass
类的一部分?
我正在尝试创建相当于以下代码:
class MyClass {
constructor(){}
myMethod(){}
}
不,不可能在 class
声明中引用给定的值。
但是, class
语法主要是语法糖,原型继承一直工作。您可以在类定义之后简单地将该方法放在原型对象上:
import {myMethod} from'./methodFile';
class MyClass {
...
}
MyClass.prototype.myMethod = myMethod;
如果您的方法需要使用 super
您将要使用 .toMethod
方法。
I'm creating a method in one module:
export function myMethod() {}
And instantiating a class in another module:
import {myMethod} from './methodFile';
class MyClass {
constructor() {}
myMethod // doesn't work
}
Is it possible to use myMethod
as part of the MyClass
class?
I'm trying to create the equivalent of the following code:
class MyClass {
constructor() {}
myMethod() {}
}
No, it is impossible to reference given values in class
declarations.
However, class
syntax is mostly syntactic sugar, and prototype inheritance works as always. You can simply put the method on the prototype object after the class definition:
import {myMethod} from './methodFile';
class MyClass {
…
}
MyClass.prototype.myMethod = myMethod;
If your method needs to use super
, you'll want to use the .toMethod
method.
这篇关于是否可以在ES2015中导入类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!