Problem Statement
What does the new keyword do in JavaScript?
Explanation
The new keyword performs four steps when creating an object:
Step 1: Creates a new empty object.
Step 2: Sets the prototype of the new object to the constructor's prototype property.
Step 3: Calls the constructor function with this bound to the new object.
Step 4: Returns the new object, unless the constructor explicitly returns another object.
This is how object-oriented programming works in JavaScript before ES6 classes.
Forgetting new when calling a constructor can cause bugs because this will refer to the global object instead.
Code Solution
SolutionRead Only
// Constructor function
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log('Hi, I am ' + this.name);
};
// Using new keyword
const john = new Person('John', 30);
// What new does:
// 1. Creates empty object: {}
// 2. Sets prototype: object.__proto__ = Person.prototype
// 3. Calls Person with this = object: Person.call(object, 'John', 30)
// 4. Returns object
console.log(john.name); // 'John'
console.log(john.age); // 30
john.greet(); // 'Hi, I am John'
// Check prototype
console.log(john.__proto__ === Person.prototype); // true
console.log(john instanceof Person); // true
// Forgetting new (common mistake)
const jane = Person('Jane', 25); // Forgot new!
console.log(jane); // undefined
console.log(window.name); // 'Jane' (polluted global!)
// Manual implementation of new
function myNew(constructor, ...args) {
// Step 1: Create empty object
const obj = {};
// Step 2: Set prototype
Object.setPrototypeOf(obj, constructor.prototype);
// Step 3: Call constructor
const result = constructor.apply(obj, args);
// Step 4: Return object (or result if object)
return typeof result === 'object' && result !== null ? result : obj;
}
const bob = myNew(Person, 'Bob', 35);
console.log(bob.name); // 'Bob'
bob.greet(); // 'Hi, I am Bob'