Accessing variables in a constructor function using a prototype method with JavaScript?


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

Updated on: 07-Sep-2020

678 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements