Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Accessing variables in a constructor function using a prototype method with JavaScript?
In JavaScript constructor functions, you can access instance variables from prototype methods using the this keyword. Prototype methods share behavior across all instances while maintaining access to individual instance data.
How Constructor Functions Work
When you create a constructor function, instance variables are defined using this.propertyName. Prototype methods can then access these variables through this.
Example
function Customer(fullName){
this.fullName = fullName;
}
Customer.prototype.setFullName = function(newFullName){
this.fullName = newFullName;
}
Customer.prototype.getFullName = function(){
return this.fullName;
}
var customer = new Customer("John Smith");
console.log("Initial name: " + customer.fullName);
customer.setFullName("David Miller");
console.log("Updated name: " + customer.getFullName());
Initial name: John Smith Updated name: David Miller
Multiple Instances Example
Each instance maintains its own variable values while sharing the same prototype methods:
function Customer(fullName, age){
this.fullName = fullName;
this.age = age;
}
Customer.prototype.getInfo = function(){
return this.fullName + " is " + this.age + " years old";
}
Customer.prototype.updateAge = function(newAge){
this.age = newAge;
}
var customer1 = new Customer("Alice Johnson", 25);
var customer2 = new Customer("Bob Wilson", 30);
console.log(customer1.getInfo());
console.log(customer2.getInfo());
customer1.updateAge(26);
console.log("After update: " + customer1.getInfo());
console.log("Customer2 unchanged: " + customer2.getInfo());
Alice Johnson is 25 years old Bob Wilson is 30 years old After update: Alice Johnson is 26 years old Customer2 unchanged: Bob Wilson is 30 years old
Key Points
-
thisin prototype methods refers to the specific instance calling the method - Instance variables are unique to each object created from the constructor
- Prototype methods are shared across all instances, saving memory
- You can both read and modify instance variables from prototype methods
Conclusion
Use this in prototype methods to access instance variables from constructor functions. This approach provides efficient method sharing while maintaining individual instance data.
Advertisements
