How to instantiate a javascript class in another js file?
Solution 1:
It depends on what environment you're running in. In a web browser you simply need to make sure that file1.js
is loaded before file2.js
:
<script src="file1.js"></script>
<script src="file2.js"></script>
In node.js, the recommended way is to make file1 a module then you can load it with the require
function:
require('path/to/file1.js');
It's also possible to use node's module style in HTML using the require.js library.
Solution 2:
// Create Customer class as follows:
export default class Customer {
getName() {
return 'stackoverflow';
}
}
// Import the class
// no need for .js extension in path cos it gets inferred automatically
import Customer from './path/to/Customer';
// OR
const Customer = require('./path/to/Customer')
// Use the class
var customer = new Customer();
var name = customer.getName();
Solution 3:
You can export your methods to access from other files like this:
file1.js
var name = "Jhon";
exports.getName = function() {
return name;
}
file2.js
var instance = require('./file1.js');
var name = instance.getName();