JavaScript Object Constructors
Object constructors are templates for creating multiple objects with similar properties and methods. By defining a constructor function, you can reuse the blueprint to instantiate new objects efficiently.
Key Topics
- Constructor Functions
- Creating Object Instances
- Adding Methods to Constructors
- JavaScript Usage in DOM
- Key Takeaways
Constructor Functions
A constructor function uses the this
keyword to define properties and is invoked with the new
keyword to create object instances.
function Person(name, age) {
this.name = name;
this.age = age;
}
let john = new Person("John", 30);
console.log(john);
Output
> Person { name: "John", age: 30 }
Explanation: The Person
constructor defines a template for creating person objects. Calling new Person("John", 30)
returns a new instance with specified properties.
Creating Object Instances
By using the new
keyword multiple times, you can easily create multiple instances sharing the same structure but different values.
let alice = new Person("Alice", 25);
let bob = new Person("Bob", 40);
console.log(alice);
console.log(bob);
Output
> Person { name: "Alice", age: 25 }
> Person { name: "Bob", age: 40 }
Explanation: Using the same constructor, Alice
and Bob
instances are created with their respective properties, illustrating the reusability of constructor functions.
Adding Methods to Constructors
Methods can be added to the constructor's prototype
to ensure all instances share the same method definition.
Person.prototype.introduce = function() {
return "My name is " + this.name;
};
console.log(john.introduce());
Output
> My name is John
Explanation: By adding introduce
to Person.prototype
, all Person
instances now have access to the same method without redefining it for each object.
JavaScript Usage in DOM
This DOM-based example shows how constructor functions can generate objects and then display their data dynamically on a webpage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Object Constructors in DOM</title>
</head>
<body>
<h1>Object Constructors Demo</h1>
<button onclick="createPerson()">Create Person</button>
<p id="info"></p>
<script>
function Person(name, age) {
this.name = name;
this.age = age;
}
function createPerson() {
let newPerson = new Person("Eva", 28);
document.getElementById("info").textContent = newPerson.name + " is " + newPerson.age + " years old";
}
</script>
</body>
</html>
Key Takeaways
- Constructor Functions: Define templates for creating multiple objects.
- Instances: Use
new
to create objects with shared structure. - Prototype Methods: Add methods to the constructor's prototype for reusability.
- DOM Usage: Dynamically instantiate objects and display their data on webpages.