简体   繁体   English

如何使用Node require在另一个Javascript文件中定义类的功能?

[英]How do you define a function of a class in another Javascript file using Node require?

Let's say I have a class A defined in its own JavaScript file, like this: 假设我在自己的JavaScript文件中定义了一个类A ,如下所示:

A.js A.js

class A {
    constructor() {
        // blah blah blah
    }
    func() {
        // a long function
    }
}

If I have a function (eg func() ) that I want to be contained in its own file (for organizational purposes), how would I accomplish this? 如果我有一个函数(例如func() )要包含在其自己的文件中(出于组织目的),我将如何实现?

What I want is something like this: 我想要的是这样的:

A.js A.js

class A {
    constructor() {
        this.func = {};
    }
} exports.A = A;

ADefinition.js ADefinition.js

var A = require('./A.js');
A.func = () => {
    // a long function
}

This obviously doesn't work, but how would one accomplish this? 这显然是行不通的,但是如何做到这一点呢?

Classes are mostly just syntax sugar. 类大多只是语法糖。 In ES5, you define prototype functions by assigning to the prototype: 在ES5中,您可以通过分配给原型来定义原型功能:

function A() {
}
A.prototype.func = function() {
}

Classes can work the same way: 类可以以相同的方式工作:

var A = require('./A.js');
A.prototype.func = () => {
    // a long function
}

Though, note that if you use an arrow function, you won't have access to the instance - you may well need a full-fledged function instead: 不过,请注意,如果使用箭头功能,则将无法访问该实例-您可能需要一个功能完善的功能:

A.prototype.func = function() {
    // a long function
};

Also, personally, I think I'd prefer to put func on the class next to the class definition for code clarity, rather than running a module that performs side effects (like your current code is attempting to do), for example: 另外,就我个人而言,我认为我希望将func放在类定义旁边的类上, 提高代码的清晰度,而不是运行执行副作用的模块(例如您当前的代码正在尝试做的事情),例如:

const func = require('./func.js');
class A {
  constructor() {
  }
}
A.prototype.func = func;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM