JavaScript Constructor & the new Operator

JavaScript Constructor & the new Operator

JavaScript Constructor & the new Operator

In JavaScript, the constructor function and the new operator are used to create objects efficiently.

1️⃣ What is a Constructor Function?

A constructor function is a regular function used to create multiple objects with the same properties and methods.

🔹 Naming Convention: Constructor functions start with a capital letter.
🔹 Must be used with new to create objects.

✅ Example: Creating a Constructor Function

function Person(name, age) { this.name = name; this.age = age; this.introduce = function() { return `Hi, I'm ${this.name} and I'm ${this.age} years old.`; }; } const person1 = new Person("Alice", 25); const person2 = new Person("Bob", 30); console.log(person1.introduce()); // "Hi, I'm Alice and I'm 25 years old." console.log(person2.introduce()); // "Hi, I'm Bob and I'm 30 years old."

📌 Key Points:
this.name = name; → Assigns properties to the object.
this.introduce = function() {...} → Adds a method.
new Person("Alice", 25); → Creates a new object.

2️⃣ How the new Operator Works

When calling a function with new, JavaScript does four things automatically:

  1. Creates a new empty object: {}
  2. Sets this to reference that object
  3. Adds properties & methods to the object
  4. Returns the new object

Example without new:

function Car(brand) { this.brand = brand; } const car = Car("Toyota"); // ❌ Missing "new", returns undefined console.log(car); // undefined

Example with new:

const car2 = new Car("Toyota"); console.log(car2.brand); // ✅ "Toyota"

3️⃣ Adding Methods to the Prototype

Instead of defining methods inside the constructor (which creates a new copy for every object), use prototype to save memory.

function Animal(type) { this.type = type; } // Adding method to prototype Animal.prototype.speak = function() { return `The ${this.type} makes a sound.`; }; const dog = new Animal("dog"); console.log(dog.speak()); // "The dog makes a sound."

📌 Why use prototype?
Saves memory (single method shared by all objects)
Efficient performance

4️⃣ Checking if an Object was Created with new

Sometimes, a function might be called without new by mistake. You can check if new was used with instanceof.

function User(name) { if (!(this instanceof User)) { return new User(name); // Automatically call with "new" } this.name = name; } const user1 = new User("Charlie"); const user2 = User("David"); // Called without "new", still works console.log(user1.name); // "Charlie" console.log(user2.name); // "David"

📌 instanceof checks if an object was created from a constructor.

5️⃣ Returning a Custom Object from a Constructor

Normally, constructors return this automatically. But if you return an object, it replaces this.

function CustomObject() { return { message: "I am a custom object!" }; } const obj = new CustomObject(); console.log(obj.message); // "I am a custom object!"

📌 If a primitive value is returned, it's ignored.

6️⃣ Summary

Constructor functions create multiple objects
Use new to create an object
Methods should go inside prototype for efficiency
Use instanceof to check object creation
Returning an object from a constructor replaces this

🚀 Now you’re a pro at JavaScript constructors & new! Let me know if you need more examples. 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close