Tarak Tarak - 3 months ago 26
Javascript Question

How to instantiate a 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 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?

Answer

Seems to be working fine over here (download).

Take note that you'll need to include file1.js before you include file2.js .