0

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?

2
  • 1
    Just add the function to the prototype. Commented Mar 10, 2019 at 19:28
  • just to make sure I understand this, would I do A.prototype.func = () => {}? Commented Mar 10, 2019 at 19:30

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Doing this gives me the following error message: TypeError: Cannot read property 'prototype' of undefined
Works fine for me: codesandbox.io/s/k55044o5z3 If you're still using your side-effects code, you'll need to assign A to the exports themselves, otherwise A will just be a property of the object you're exporting. eg module.exports = A or const { a } = require('./A.js');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.