DEV Community

_Khojiakbar_
_Khojiakbar_

Posted on • Edited on

Constructor Function ?🧐

Image description

A constructor function in JavaScript is a special function used to create and initialize objects. It's like a blueprint for creating multiple similar objects. When you use the new keyword with a constructor function, it creates a new object based on that blueprint.

Example

  • Define the constructor function
function Pet(name, type) {
    this.name = name;
    this.type = type;
}
Enter fullscreen mode Exit fullscreen mode
  • Create new pet objects
let pet1 = new Pet("Fluffy", "Cat");
let pet2 = new Pet("Buddy", "Dog");

console.log(pet1.name); // Output: Fluffy
console.log(pet1.type); // Output: Cat

console.log(pet2.name); // Output: Buddy
console.log(pet2.type); // Output: Dog
Enter fullscreen mode Exit fullscreen mode
  • Adding methods to constructor functions
function Pet(name, type) {
    this.name = name;
    this.type = type;

    this.describe = function() {
        return `${this.name} is a ${this.type}.`;
    };
}

let pet1 = new Pet("Fluffy", "Cat");
let pet2 = new Pet("Buddy", "Dog");

console.log(pet1.describe()); // Output: Fluffy is a Cat.
console.log(pet2.describe()); // Output: Buddy is a Dog.
Enter fullscreen mode Exit fullscreen mode

Extra sample

// Define the object
function Phone (name, color, memory, price) {
    this.name = name,
    this.color = color,
    this.price = price,
    this.memory = memory,
    this.tellAbout = function() {
        return `${this.name} has ${this.memory}GB, and its color is ${this.color}.`
    }
}
// Create the object
const iPhone_13 = new Phone('iPhone 13', 'blue', 256, 7000000);
console.log(iPhone_13.tellAbout()); // iPhone 13 has 256GB, and its color is blue.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)