- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- JavaScript Array prototype Constructor
- How to invoke a function with a function constructor in JavaScript?
- How to define a JavaScript function using Function() Constructor?
- How to invoke a JavaScript Function with 'new' Function Constructor?
- What is a constructor method in JavaScript?
- Accessing a parent Element using JavaScript
- Accessing an array returned by a function in JavaScript
- Class with a constructor to initialize instance variables in Java
- How to access variables declared in a function, from another function using JavaScript?
- Add a method to a JavaScript object constructor?
- Another method other than a constructor in a JavaScript class?
- How to access a JavaScript object using its own prototype?
- Reference to a constructor using method references in Java8
- Explain 'Not a constructor function' error in JavaScript?
- Adding a function for swapping cases to the prototype object of strings - JavaScript

Advertisements