Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate a javascript class in another js file?

Tags:

javascript

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 am getting exception: Customer is undefined, not a constructor.

But when i create a customer object in file2.js and pass it to file1.js then its working .

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 new Customer(). How can i achieve that?

like image 824
Tarak Avatar asked Oct 10 '12 05:10

Tarak


People also ask

How do you instantiate a class in JavaScript?

The new operator instantiates the class in JavaScript: instance = new Class() . const myUser = new User(); new User() creates an instance of the User class.

Can I call a JS function from another JS file?

As long as both are referenced by the web page, yes. You simply call the functions as if they are in the same JS file.

How do you refer JavaScript from another file?

Save the script file with a . js extension, and then refer to it using the src attribute in the <script> tag. Note: The external script file cannot contain the <script> tag.

Can JavaScript be in a separate file?

You can keep the JavaScript code in a separate external file and then point to that file from your HTML document.


2 Answers

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.

like image 52
slebetman Avatar answered Sep 27 '22 22:09

slebetman


// 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(); 
like image 33
ColinWa Avatar answered Sep 27 '22 22:09

ColinWa