Sub topic 8
Constructors and the new Keyword
This chapter assumes you know how plain function calls and method calls set this, and how bind returns a function with a fixed this. Here you will see the fourth way a call can set this: calling a function with new.
What new Does
Any regular function can act as a constructor. A constructor is just a function you call with new. Writing the new keyword before the call makes JavaScript run four steps:
- It creates a fresh, empty object.
- It links that object's prototype to the function's
prototypeproperty. - It calls the function with
thisset to the new object. - It returns the new object, unless the function itself returns a different object.
Step 3 matters most for this. Inside the constructor, this is a brand-new object that did not exist before the call. It is not the global object, it is not an object before a dot, and it is not anything you passed in.
function Box(value) {
this.value = value;
}
Box.prototype.describe = function () {
return `Box holding ${this.value}`;
};
const b1 = new Box(1);
console.log(b1.value); // 1
console.log(b1.describe()); // 'Box holding 1'
console.log(Object.getPrototypeOf(b1) === Box.prototype); // trueCalling b1.describe() is an ordinary method call, so this is b1. The new rule applies only to the constructor call itself.
new and Bound Functions
A function produced by bind can still be called with new. In that case new wins: the this you bound gets ignored, and the constructor receives the fresh object. Any arguments you bound in advance are still passed.
function Box(value) {
this.value = value;
}
const BoundBox = Box.bind({ value: 'ignored' });
const b2 = new BoundBox(42);
console.log(b2.value); // 42, new overrides the bound this
console.log(b2 instanceof Box); // true
const BoxOfSeven = Box.bind(null, 7);
console.log(new BoxOfSeven().value); // 7, bound arguments still applyBound functions have no prototype property of their own. Objects created through them link to the original function's prototype, which is why b2 instanceof Box is true.
Common Errors
Forgetting new
If you call a constructor without new, the default binding rule applies.
'use strict';
function Point(x) {
this.x = x;
}
try {
Point(5); // this is undefined in strict code
} catch (err) {
console.log(err instanceof TypeError); // true
}In sloppy mode the same call quietly creates a global variable x and returns undefined. You can guard against this with new.target. It is undefined when the function runs without new:
function Point(x) {
if (!new.target) {
return new Point(x);
}
this.x = x;
}
console.log(Point(5).x); // 5Classes handle this for you. Calling a class without new always throws.
Returning an Object from a Constructor
If a constructor returns an object, that object replaces this as the result. Primitive return values are ignored.
function Weird() {
this.tag = 'mine';
return { tag: 'replaced' };
}
function Fine() {
this.tag = 'mine';
return 42; // ignored
}
console.log(new Weird().tag); // 'replaced'
console.log(new Fine().tag); // 'mine'Using an Arrow Function as a Constructor
Arrow functions have no this of their own and no prototype, so they cannot be constructors.
const Make = (v) => { this.v = v; };
try {
new Make(1);
} catch (err) {
console.log(err.message); // 'Make is not a constructor'
}Methods defined with shorthand syntax ({ m() {} }) cannot be constructors either.
| Call form | `this` inside the function |
|---|---|
| `new Fn()` | Fresh object linked to `Fn.prototype` |
| `new (Fn.bind(obj))()` | Fresh object; `obj` ignored |
| `Fn()` in strict code | `undefined` |
| `Fn()` in sloppy code | `globalThis` |
Exercise
Given function User(name) { this.name = name; } and const Admin = User.bind({ name: 'root' }, 'ada');, what does new Admin('bob').name evaluate to, and why?
Show answer
It evaluates to 'ada'. new ignores the bound this ({ name: 'root' }) and passes a fresh object instead. The bound leading argument 'ada' still comes first, so name is 'ada' and the extra argument 'bob' is unused.
Exercise
A sloppy-mode script calls function Counter() { this.count = 0; } as const c = Counter();. What are the values of c and globalThis.count?
Show answer
c is undefined because Counter returns nothing and no new object was created. Without new, default binding sets this to globalThis in sloppy mode, so globalThis.count is 0.