是否可以在ES2015中导入类方法 [英] Is it possible to import class methods in ES2015
问题描述
我在一个模块中创建一个方法:
导出函数myMethod(){}
在另一个模块中实例化一个类:
code> import {myMethod} from'./methodFile';
class MyClass {
constructor(){}
myMethod //不工作
}
是否可以使用 myClass
类的一部分 myMethod
我尝试创建相当于以下代码的代码:
class MyClass {
constructor(){}
myMethod(){}
}
不,不可能引用 class
声明中的给定值。
但是, class
语法主要是语法糖,并且原型继承总是起作用。你可以简单地把方法放在类定义之后的原型对象上:
import {myMethod} from'./methodFile';
class MyClass {
...
}
MyClass.prototype.myMethod = myMethod;
如果您的方法需要使用 super
您需要使用 .toMethod
方法。 p>
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屋!