firetto
firetto

Reputation: 13

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:

A.js

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

If I have a function (e.g. func()) that I want to be contained in its own file (for organizational purposes), how would I accomplish this?

What I want is something like this:

A.js

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

ADefinition.js

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

This obviously doesn't work, but how would one accomplish this?

Upvotes: 0

Views: 120

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370989

Classes are mostly just syntax sugar. In ES5, you define prototype functions by assigning to the prototype:

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:

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

Upvotes: 1

Related Questions