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

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more