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
How to add a property, method to a JavaScript constructor?
In JavaScript, you can add properties and methods to constructor functions using the prototype property. This allows all instances of the constructor to share these additions.
Syntax
// Add a property
ConstructorName.prototype.propertyName = value;
// Add a method
ConstructorName.prototype.methodName = function() {
// method body
};
Example: Adding Property and Method to Constructor
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
color: green;
}
</style>
</head>
<body>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to add property, method to constructor</h3>
<script>
let resEle = document.querySelector(".result");
function Human(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
let obj = new Human('Rohan', 'Sharma');
document.querySelector(".Btn").addEventListener("click", () => {
// Add method to constructor prototype
Human.prototype.welcome = function() {
return 'Welcome ' + this.firstName + ' ' + this.lastName;
}
// Add property to constructor prototype
Human.prototype.age = 22;
resEle.innerHTML = 'Adding property to constructor: age<br>' + obj.age + '<br>';
resEle.innerHTML += 'Adding function to constructor: welcome()<br>' + obj.welcome() + '<br>';
});
</script>
</body>
</html>
Output
The above code will produce the following output:
On clicking the 'CLICK HERE' button:
How It Works
When you add properties or methods to a constructor's prototype, all instances created from that constructor automatically inherit these additions. This is because JavaScript uses prototypal inheritance to look up properties and methods.
Key Points
- Use
ConstructorName.prototype.propertyNameto add properties - Use
ConstructorName.prototype.methodNameto add methods - All existing and future instances will have access to these additions
- This approach is memory-efficient as methods are shared across instances
Conclusion
Adding properties and methods to constructor prototypes is a powerful feature in JavaScript. It enables dynamic extension of objects and promotes code reusability across all instances.
Advertisements
