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?
The new operator instantiates the class in JavaScript: instance = new Class() . const myUser = new User(); new User() creates an instance of the User class.
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.
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.
You can keep the JavaScript code in a separate external file and then point to that file from your HTML document.
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.
// 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With