0
0
JavascriptHow-ToBeginner · 4 min read

How to Create Constructor in JavaScript: Simple Guide

In JavaScript, you create a constructor by defining a function or a class with a special method called constructor. This sets up new objects with properties when you use the new keyword.
📐

Syntax

A constructor can be created using a function or a class. In a function constructor, you define properties using this. In a class, you use the constructor method to initialize properties.

  • Function constructor: A regular function used with new.
  • Class constructor: A special constructor method inside a class.
javascript
function Person(name, age) {
  this.name = name;
  this.age = age;
}

class Animal {
  constructor(type, sound) {
    this.type = type;
    this.sound = sound;
  }
}
💻

Example

This example shows how to create objects using both a function constructor and a class constructor. It demonstrates how properties are set and accessed.

javascript
function Person(name, age) {
  this.name = name;
  this.age = age;
}

const person1 = new Person('Alice', 30);
console.log(person1.name); // Alice
console.log(person1.age);  // 30

class Animal {
  constructor(type, sound) {
    this.type = type;
    this.sound = sound;
  }
}

const animal1 = new Animal('Dog', 'Bark');
console.log(animal1.type);  // Dog
console.log(animal1.sound); // Bark
Output
Alice 30 Dog Bark
⚠️

Common Pitfalls

Common mistakes include forgetting to use the new keyword, which causes this to refer to the global object or be undefined. Another mistake is not using this to assign properties inside the constructor.

Always use new when calling a constructor function or class to create a new object.

javascript
function Person(name) {
  // Wrong: missing 'this' means no property set on the object
  name = name;
}
const p = new Person('Bob');
console.log(p.name); // undefined

// Correct way
function PersonCorrect(name) {
  this.name = name;
}
const p2 = new PersonCorrect('Bob');
console.log(p2.name); // Bob
Output
undefined Bob
📊

Quick Reference

Remember these key points when creating constructors in JavaScript:

  • Use function or class syntax.
  • Inside constructors, assign properties with this.propertyName = value.
  • Always use new to create an instance.
  • Class constructors use the special constructor method.

Key Takeaways

Use the new keyword to create objects with constructors.
Assign properties inside constructors using this.property = value.
Function constructors and class constructors both create objects but use different syntax.
For classes, define a constructor method to initialize properties.
Avoid forgetting new or missing this assignments to prevent bugs.