The New Keyword And The Function Object Duality
The 'new' keyword is every interviewer's favorite question. It automates the tedious parts of object creation and prototype bonding.
Automation is the heart of Object-Oriented Programming. We've manually created objects, manually set up prototype links, and manually handled context. It's a lot of work. To speed this up, JavaScript provides the new keyword.
The Essentials
- Function-Object Duality: In JavaScript, every function is also an object.
- The
.prototypeObject: Every function has an object property calledprototypewhere shared methods should live. - Automation: The
newkeyword automates the creation, linking, and returning of objects. - Capitalization Convention: Functions intended for use with
neware capitalized (e.g.,UserCreator) to warn other developers.
ExpandAutomation of the new keyword
The "Two-Headed Monster"
To understand new, you must realize that functions are special. You can call them like a function, but you can also treat them like an object.
function multiplyBy2(num) {
return num * 2;
}
multiplyBy2.stored = 5; // Adding a property to a function!The Default Prototype
Every function object automatically comes with a property called prototype. This is just a regular, empty object. When we use new, JavaScript expects to find our shared functions in this specific "bucket."
Solution 3: The new Keyword
When we put new in front of a function call, it intercedes and performs four major steps automatically:
function UserCreator(name, score) {
this.name = name;
this.score = score;
}
UserCreator.prototype.increment = function() {
this.score++;
};
const user1 = new UserCreator("Denver", 3);What new does under the hood:
- Create
this: It creates a brand new empty object and labels itthisinside the function. - Link the Prototype: It sets the hidden
[[Prototype]]link of that new object to the function's.prototypeobject. - Execute: It runs your code (e.g.,
this.name = name). - Return: It automatically returns the
thisobject.
Step 1:We store the shared method in the function's 'object' side under .prototype.
The Danger: Forgetting new
If you call UserCreator("Denver", 3) without the new keyword:
- No object is created.
thisdefaults towindow.- You accidentally create
window.nameandwindow.score. - The function returns
undefined.
This is why the uppercase convention (UserCreator) is so important: it is a signal to your team that this function requires the new keyword to behave correctly.
But even with new, the syntax of adding methods to .prototype feels a bit disjointed. In the next part, we'll see how ES6 Classes wrap all of this into one clean, modern structure.
Further Reading and Watching
- Video: The new Keyword in Depth
- MDN: new operator
- Concept: Constructor functions
Keep reading