DEV Community

_Khojiakbar_
_Khojiakbar_

Posted on • Edited on

1

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series