Rot*_*eti 9 javascript ecmascript-6 es6-module-loader
假设我有一个像这样的简单类fileA.js:
class foo {
constructor(x) {
this.name = x
}
fooMethod(x) {
return x + 'hello';
}
}
Run Code Online (Sandbox Code Playgroud)
我想导入和使用fooMethod在fileB.js这样的:
import { fooMethod } from './fileA';
class bar() {
...
barMethod(x) {
return fooMethod(x);
}
}
Run Code Online (Sandbox Code Playgroud)
我怎么写exportin fileA来实现这个?
你必须在原型上导出它.但请记住,如果你这样做,你将不会在类/对象上下文中调用该函数:
export foo.prototype. fooMethod
Run Code Online (Sandbox Code Playgroud)
但是我建议你不要这样做.
好的,由于你的评论,你想要一个很好的方法来为两个类提供一个共同的功能,它不会扩展相同的基类.一种简单的方法是从两个类导入实用程序函数:
foo.js
export function foo() {
return this.name;
}
Run Code Online (Sandbox Code Playgroud)
a.js
import {foo} from 'foo';
export class A extends BaseA {
foo() {
foo.apply(this, arguments);
}
}
Run Code Online (Sandbox Code Playgroud)
b.js
import {foo} from 'foo';
export class B extends BaseB {
foo() {
foo.apply(this, arguments);
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个很好的模式,适用于单个函数,但如果要应用更复杂的功能,则有限制.实现这一目标的一个好方法是混合模式:
foo.js
export default superClass => class extends superClass {
foo() {
return this.name;
}
};
Run Code Online (Sandbox Code Playgroud)
a.js
import foo from 'foo';
export class A extends foo(BaseA) {
..
}
Run Code Online (Sandbox Code Playgroud)
b.js
import foo from 'foo';
export class B extends foo(BaseB) {
..
}
Run Code Online (Sandbox Code Playgroud)
这将使您的混音在您的类'A'/'B'和'BaseA'/'BaseB'之间创建一个新的匿名类,它提供了通用功能foo.
您必须将其导出为单独的变量/常量,如下所示:
class Foo {
fooMethod() {};
}
export const fooMethod = Foo.prototype.fooMethod;
Run Code Online (Sandbox Code Playgroud)
编辑
事实证明,您并不需要实例方法(您不使用this).我只想定义并使用常规函数:
export function fooMethod(x) {
return x + 1;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以通过实例化类来导出和导入类方法,这显然将其转换为对象,然后通过从下面的新实例化对象检查代码示例中解构它们来导出每个方法。
像这样销毁和导出对象方法:
class foo {
doSomething() {
// some stuffs
}
doAnotherThing() {
// do something else
}
}
export const { doSomething, doAnotherThing } = new foo()
Run Code Online (Sandbox Code Playgroud)
然后在您要导入方法的文件中执行以下操作:
import { doSomething, doAnotherThing } from '../class/file/directory'
doSomething() // calls the method
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助
| 归档时间: |
|
| 查看次数: |
26363 次 |
| 最近记录: |