Javascript constructor functions
Created By: chatGPT
JavaScript provides a way to create objects through constructor functions. Constructor functions are regular functions but are designed to initialize new objects. When you define a constructor function, you typically name it with a capital letter to distinguish it from regular functions. Let's take a look at how to create and use a constructor function.
function Person(name, age) {
this.name = name;
this.age = age;
this.introduce = function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};
}
const john = new Person('John', 30);
john.introduce(); // Output: Hello, my name is John and I am 30 years old.
To create an instance of an object using the constructor function, you use the new keyword. This keyword creates a new object, and the constructor function is called with that object as its context (the value of this inside the function).
const jane = new Person('Jane', 25);
jane.introduce(); // Output: Hello, my name is Jane and I am 25 years old.
You can also add methods to the constructor's prototype. This improves memory efficiency since all instances share the same method rather than having their own copy. This is particularly useful for operations that do not require data specific to each instance.
Person.prototype.greet = function() {
console.log(`Greetings from ${this.name}!`);
};
john.greet(); // Output: Greetings from John!
Another interesting feature of constructor functions is inheritance. You can create a new constructor function that inherits from a parent constructor by using
By utilizing constructor functions, you can create well-structured and maintainable code in JavaScript. They allow for the creation of multiple instances with the same properties and methods while also enabling inheritance, which is essential for building scalable applications.Object.create
. This enables you to extend objects easily.function Employee(name, age, position) {
Person.call(this, name, age);
this.position = position;
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.introducePosition = function() {
console.log(`I am a ${this.position}.`);
};
const mike = new Employee('Mike', 40, 'Manager');
mike.introduce(); // Output: Hello, my name is Mike and I am 40 years old.
mike.introducePosition(); // Output: I am a Manager.