Noob in JS here.
Let's say I have a js file where the contents are like
function a(){}
a.prototype.method1 = function() { ... };
a.prototype.method2 = function() { ... };
function b(){}
b.prototype.method3 = function() { ... };
b.prototype.method4 = function() { ... };
module.exports = new a();
module.exports = new b();
In this file, I've function definition. In the next file, I'm trying to access the methods below
var x = require('./file.js');
x.a.method1(); //Not working
x.method1(); //Not working
But both types of accessing result in error for me. Can you please help me with steps on how to access the methods correctly?
And I can access those functions if I try to have only 1 export in one file. But I want it to be like this. 2 exports in a same file.
CodePudding user response:
The problem is that you're replacing the exports
property twice:
module.exports = new a();
module.exports = new b();
As a result, you're only exporting one thing: an instance of b
, which has no method1
on it.
Instead, write to properties on the exports
object:
module.exports.a = new a();
module.exports.b = new b();
Then:
const x = require('./file.js');
x.a.method1();
// ...
or more typically, with destructuring so you don't need x
:
const {a, b} = require('./file.js');
a.method1();
// ...
All of that said: That syntax is the old CommonJS module system. I suggest you learn the newer standard syntax, "ESM" (ECMAScript Modules), added to the JavaScript specification in ES2015:
function A() {
}
A.prototype.method1 = function() { /* ... */ };
A.prototype.method2 = function() { /* ... */ };
function B(){}
B.prototype.method3 = function() { /* ... */ };
B.prototype.method4 = function() { /* ... */ };
export const a = new A();
export const b = new B();
Also note that I've made the constructor functions start with a capital letter, which is the standard convention in JavaScript.
The import would be:
import { a, b } from "./file.js";
a.method1();
// ...
To do that, you add "type": :"module"
to your package.json
(or use the .mjs
file extension, see the linked docs for details). Note though that a large number of npm
packages haven't been updated to support ESM yet (not least because supporting both took a while to nail down and is a bit of a pain), so in some cases you have to jump through some (minor) hoops to use them; more here.
(You might also look at the class
syntax, which provides a more concise and powerful way to write constructor functions and their associated .prototype
objects.)
CodePudding user response:
module.exports = {
a,
b
}
Call it from other file:
const {a, b} = require("./file.js");