For this, use a “prototype”. JavaScript objects inherit properties and methods from a prototype. For accessing variables, we have also used the “this” in JavaScript.
Example
function Customer(fullName){
this.fullName=fullName;
}
Customer.prototype.setFullName = function(newFullName){
this.fullName=newFullName;
}
var customer=new Customer("John Smith");
console.log("Using Simple Method = "+ customer.fullName);
customer.setFullName("David Miller");
console.log("Using Prototype Method = "+customer.fullName);To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo79.js.
Output
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo79.js Using Simple Method = John Smith Using Prototype Method = David Miller