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

JavascriptWeb DevelopmentObject Oriented Programming

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.


function Customer(fullName){
Customer.prototype.setFullName = function(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.


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
Published on 07-Sep-2020 11:35:21