【问题标题】:Is it possible to import class methods in ES2015是否可以在 ES2015 中导入类方法
【发布时间】:2026-02-17 12:20:06
【问题描述】:

我正在一个模块中创建一个方法:

export function myMethod() {}

并在另一个模块中实例化一个类:

import {myMethod} from './methodFile';
class MyClass {
    constructor() {}
    myMethod // doesn't work
}

是否可以将myMethod 用作MyClass 类的一部分?

我正在尝试创建与以下代码等效的代码:

class MyClass {
    constructor() {}
    myMethod() {}
}

【问题讨论】:

    标签: javascript class ecmascript-6


    【解决方案1】:

    不,不可能在class 声明中引用给定值。

    然而,class 语法主要是语法糖,原型继承一​​如既往地工作。您可以简单地将方法放在类定义之后的原型对象上:

    import {myMethod} from './methodFile';
    class MyClass {
        …
    }
    MyClass.prototype.myMethod = myMethod;
    

    如果您的方法需要使用super,您需要使用use the .toMethod method

    【讨论】:

    • 顺便说一句,如果这是您的 methodFile 中唯一的内容,我建议您使用 default 导出。
    • 我建议在声明类是语法糖时要小心。现在转译器可能是这样的;但在内置浏览器实现中不一定如此。
    • @Phil 这是一个实现细节。关键是尽管语法不同,类并没有引入任何新概念,它们仍然只是带有原型对象的构造函数。
    【解决方案2】:

    其实可以在类内部引用外部方法:

    // in methodFile.js:
    
    module.exports = function myMethod() {
      console.log('running in the method!');
    }
    
    
    // in main file
    
    const myMethod = require('./methodFile');
    
    class MyClass {
        myMethod = myMethod;
    }
    
    const myClass = new MyClass();
    
    myClass.myMethod(); // running in the method!
    

    【讨论】: