How to instantiate javascript class in another js file?

Suppose if I define a class in file1.js

function Customer(){ this.name="Jhon"; this.getName=function(){ return this.name; }; }; 

Now, if I want to create a Customer object in file2.js

 var customer=new Customer(); var name=customer.getName(); 

I get an exception: Customer is undefined, not a constructor.

But when I create a customer object in file2.js and pass it to file1.js, then it works.

 file1.js function Customer(){ this.name="Jhon"; this.getName=function(){ return this.name; } } function customer(){ return new Customer(); } file2.js var customer=customer(); var name=customer.getName(); 

but I want to create a customer object in file1.js using the new Customer (). How can I achieve this?

+18
source share
6 answers

It depends on what environment you work in. In a web browser, you just need to make sure file1.js loaded before file2.js :

 <script src="file1.js"></script> <script src="file2.js"></script> 

In node.js, the recommended way is make file1 a module , then you can load it using the require function:

 require('path/to/file1.js'); 

It is also possible to use the node module style in HTML using the require.js library.

+16
source

You can export your access methods from other files, such as:

file1.js

 var name = "Jhon"; exports.getName = function() { return name; } 

file2.js

 var instance = require('./file1.js'); var name = instance.getName(); 
+6
source

Make sure dom is loaded before running your code in file2 ... If you are using jQuery:

 $(function(){ var customer=customer(); var name=customer.getName(); }); 

Then it does not matter in which order the files are located, the code will not work until all the files have been downloaded.

+4
source

If you use javascript in HTML, you should include file1.js and file2.js in your html:

 <script src="path_to/file1.js"></script> <script src="path_to/file2.js"></script> 

Note. file1 must be first before file2 .

+2
source

Possible suggestions to make it work:

Some modifications (U forgot to include a semicolon in the statement this.getName=function(){...} , it should be this.getName=function(){...}; )

 function Customer(){ this.name="Jhon"; this.getName=function(){ return this.name; }; } 

(This may be one of the problems.)

and

Make sure U binds JS files in the correct order

 <script src="file1.js" type="text/javascript"></script> <script src="file2.js" type="text/javascript"></script> 
+2
source
 // Create Customer class as follows: export default class Customer {} // Import the class // no need for .js extension in path cos 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(); 
+1
source

All Articles