使用ES6模块导出/导入单类方法? [英] export / import single class method using ES6 modules?
问题描述
假设我在fileA.js
中有一个像这样的简单类:
Let's say I have a simple class like this in fileA.js
:
class foo {
constructor(x) {
this.name = x
}
fooMethod(x) {
return x + 'hello';
}
}
我想像这样在fileB.js
中导入和使用fooMethod
:
And I want to import and use fooMethod
in fileB.js
like this:
import { fooMethod } from './fileA';
class bar() {
...
barMethod(x) {
return fooMethod(x);
}
}
我该如何在fileA
中编写export
来实现这一目标?
How would I write the export
in fileA
to achieve this?
推荐答案
您必须将其导出到原型中.但是请记住,如果这样做,您将不会在类/对象上下文中调用该函数:
You would have to export it on the prototype. But remember that if you do that you won't call the function in the class/object context:
export foo.prototype. fooMethod
但是我建议您不要这样做.
However I would recommend you to not to do so.
好的,由于您的评论,您希望有一个很好的方法来为两个类提供通用功能,而这些功能不会扩展同一基类.一种简单的方法是从两个类中导入实用程序函数:
Okay, due to your comment you want a good way to have a common functionality for two classes, that don't extend the same base class. One simple way is to import a utility function from two classes:
foo.js
export function foo() {
return this.name;
}
a.js
import {foo} from 'foo';
export class A extends BaseA {
foo() {
foo.apply(this, arguments);
}
}
b.js
import {foo} from 'foo';
export class B extends BaseB {
foo() {
foo.apply(this, arguments);
}
}
这是一个很好的模式,并且对于单个功能很好地工作,但是如果您想应用更复杂的功能,则存在局限性.实现此目的的一种好方法是混合模式:
This is a good pattern and works well for a single function, but has limits if you want to apply more complex functionality. A good way to achieve this is a mixing pattern:
foo.js
export default superClass => class extends superClass {
foo() {
return this.name;
}
};
a.js
import foo from 'foo';
export class A extends foo(BaseA) {
..
}
b.js
import foo from 'foo';
export class B extends foo(BaseB) {
..
}
这将使您的混合在类'A'/'B'和'BaseA'/'BaseB'之间创建一个新的匿名类,该类提供了通用功能foo
.
This will make your mixing create a new anonymous class between your class 'A'/'B' and 'BaseA'/'BaseB', which provides the common function foo
.
这篇关于使用ES6模块导出/导入单类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!