Sub topic 8
Constructors and the new Keyword
So far, this has come from the call site in one of three ways. It was the default value in a plain call, the object before the dot in a method call, or a value you passed in with call, apply, or bind. The new keyword is the fourth rule. It does not reuse an existing object for this. It creates a brand-new object and binds this to it.
This chapter assumes you know how functions, objects, and prototypes work at a basic level. It also assumes you have read the earlier chapters on default, implicit, and explicit binding, because new is easiest to understand next to those rules.
What new Actually Does
A constructor in JavaScript is an ordinary function called with new in front of it. The function body uses nothing special. The behavior comes from the call itself.
function Box(value) {
this.value = value;
}
const b1 = new Box(1);
console.log(b1.value); // 1
console.log(b1 instanceof Box); // trueWhen the engine evaluates new Box(1), it takes these steps:
- It creates a new, empty object.
- It sets that object's prototype to
Box.prototype. - It calls
Boxwiththisbound to the new object and passes along the arguments. - If
Boxreturns an object, that object is the result of the expression. Otherwise the result is the new object from step 1.
A simplified new in plain JavaScript
You can write a rough version of new using tools from earlier chapters. Object.create handles the prototype link, and apply handles the explicit this.
function myNew(Constructor, ...args) {
const obj = Object.create(Constructor.prototype);
const result = Constructor.apply(obj, args);
const isObject =
result !== null && (typeof result === 'object' || typeof result === 'function');
return isObject ? result : obj;
}
function Box(value) {
this.value = value;
}
const b = myNew(Box, 7);
console.log(b.value); // 7
console.log(b instanceof Box); // trueThis model is close but not exact. Real new refuses to run on functions that are not constructors, it supports new.target, it works with classes, and it treats bound functions specially. All of these come up later in this chapter. The model still shows the core idea. Inside a constructor, this is a fresh object whose prototype is the constructor's prototype property.
Prototype Methods and this
Constructors usually set data on this and put shared methods on the prototype. Those methods then get their this through implicit binding when called on an instance.
function Counter(start) {
this.count = start;
}
Counter.prototype.increment = function () {
this.count++;
return this.count;
};
const c = new Counter(10);
console.log(c.increment()); // 11, implicit binding: this is cHere the two rules work at different moments. new binds this while the constructor runs. After that, each call to c.increment() is an ordinary method call, so this is whatever sits before the dot. Detaching increment loses this exactly as it did in the chapter on lost bindings. Being created by new gives the instance no protection.
Return Values from Constructors
Step 4 trips people up. A constructor can replace the object that new created, but only by returning an object. Returning a primitive does nothing.
function ReturnsObject() {
this.a = 1;
return { b: 2 };
}
function ReturnsPrimitive() {
this.a = 1;
return 42;
}
function ReturnsNothing() {
this.a = 1;
}
console.log(new ReturnsObject()); // { b: 2 }
console.log(new ReturnsPrimitive()); // ReturnsPrimitive { a: 1 }
console.log(new ReturnsNothing()); // ReturnsNothing { a: 1 }| Constructor returns | Result of `new` | Notes |
|---|---|---|
| Nothing (`undefined`) | The new `this` object | The normal case |
| A primitive (`42`, `'x'`, `true`, `null`) | The new `this` object | The return value is ignored |
| An object, array, or function | The returned value | The new `this` object is thrown away |
Forgetting new
A constructor is just a function, so nothing stops you from calling it without new. That makes it a plain call, and default binding takes over.
function User(name) {
this.name = name;
}
// In a classic sloppy-mode script:
const u = User('Ada');
console.log(u); // undefined, nothing was returned
console.log(globalThis.name); // 'Ada', a global was created by accidentSloppy mode fails silently. The property lands on the global object and the variable you meant to fill gets undefined. Strict mode turns the mistake into an error, because this is undefined and assigning a property to undefined throws.
'use strict';
function User(name) {
this.name = name;
}
User('Ada'); // TypeError: Cannot set properties of undefined (setting 'name')ES modules and class bodies are always strict, so most modern code gets the loud failure. That is one practical reason the strict default from the earlier chapter matters.
Guarding with new.target
Inside a function, new.target refers to the constructor that new was applied to. In a plain call it is undefined. You can use it to reject or repair calls that forgot new.
function User(name) {
if (!new.target) {
return new User(name); // repair the call
}
this.name = name;
}
const a = new User('Ada');
const b = User('Grace');
console.log(a.name, b.name); // 'Ada' 'Grace'
console.log(b instanceof User); // trueYou could throw an error in place of the repair if you want callers to fix their code. Classes do this for you, as the next section shows.
Classes Require new
A class constructor cannot be called as a plain function. The engine checks this before running any of your code.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
const p = new Point(1, 2);
console.log(p.x, p.y); // 1 2
Point(1, 2); // TypeError: Class constructor Point cannot be invoked without 'new'In a base class, this in the constructor is the new object, just as with a constructor function. Derived classes (class B extends A) work differently. In those, this does not exist until super() returns. The chapter on classes covers this in detail.
Functions That Cannot Be Used with new
Some functions are not constructors at all. Calling new on them throws a TypeError. The mistake shows up right away at runtime instead of producing a strange object.
const arrow = () => {};
const obj = { method() {} };
async function load() {}
function* gen() {}
try { new arrow(); } catch (e) { console.log(e.message); } // arrow is not a constructor
try { new obj.method(); } catch (e) { console.log(e.message); } // obj.method is not a constructor
try { new load(); } catch (e) { console.log(e.message); } // load is not a constructor
try { new gen(); } catch (e) { console.log(e.message); } // gen is not a constructor| Function kind | Can be used with `new`? | Has a `prototype` property? |
|---|---|---|
| `function` declaration or expression | Yes | Yes |
| `class` | Yes, and only with `new` | Yes |
| Arrow function | No | No |
| Method shorthand `{ m() {} }` | No | No |
| `async function` | No | No |
| Generator `function*` | No | Yes, but it is not a constructor |
| Bound function from `bind` | Only if the original function is a constructor | No |
Arrow functions fail because they have no this of their own to bind. A later chapter covers this. Method shorthand does have its own this, but the language marks it as a method and not a constructor.
new Wins Over Implicit and Bound this
Two situations show how new ranks against the other rules. The next chapter covers precedence in full. These cases belong here because they affect how you write constructors.
new on a method reference
If a constructor is stored on an object, new obj.Ctor() still creates a fresh this. The object before the dot is used only to look up the function.
const factory = {
Make: function () {
this.made = true;
}
};
const m = new factory.Make();
console.log(m.made); // true
console.log(factory.made); // undefined, factory was not thisnew on a bound function
The bind method fixes this for normal calls. It does not fix this when the bound function is used with new. The bound this is ignored, and the new object is used instead.
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, the prototype comes from BoxThe new object's prototype comes from the original function (Box.prototype), not from the bound function, which has no prototype property. Because of this, myNew(BoundBox, 42) from earlier would throw. That is one of the cases where the simplified model falls short.
The bound this is dropped, but the bound arguments are kept. You can use this to preset constructor arguments.
function Point(x, y) {
this.x = x;
this.y = y;
}
const OnYAxis = Point.bind(null, 0); // x is always 0
const p = new OnYAxis(5);
console.log(p.x, p.y); // 0 5
console.log(p instanceof Point); // true
console.log(p instanceof OnYAxis); // true, instanceof checks the target functionCommon Errors and How to Spot Them
| Symptom | Likely cause | Fix |
|---|---|---|
| `undefined` result and a stray global variable | Constructor called without `new` in sloppy mode | Add `new`, use strict mode, or guard with `new.target` |
| `TypeError: Cannot set properties of undefined` in a constructor | Constructor called without `new` in strict code | Add `new` |
| `TypeError: X is not a constructor` | `new` used on an arrow, method shorthand, async, or generator function | Use a `function` or `class` |
| `instanceof` returns false for a fresh instance | Constructor returns its own object | Remove the object return or stop relying on `instanceof` |
| Bound `this` "doesn't work" | The bound function was called with `new` | Expected behavior, because `new` overrides `bind` |
| Method on an instance loses `this` | The method was detached after construction | Treat it like any lost binding: `bind`, an arrow wrapper, or an arrow class field |
Exercise
What does this code log, and why? function Thing() { this.kind = 'thing'; return 'not a thing'; } const t = new Thing(); console.log(t.kind, typeof t);
Show answer
It logs "thing object". The constructor returns a primitive string, and new ignores primitive return values, so the result is the freshly created this object, which has kind set to 'thing'.
Exercise
Given function Tag(prefix, label) { this.text = prefix + label; } and const owner = { text: 'owner' }; const BoundTag = Tag.bind(owner, '#');, what are new BoundTag('news').text and owner.text afterward?
Show answer
new BoundTag('news').text is '#news' and owner.text is still 'owner'. Under new, the bound this (owner) is ignored and a fresh object is used, but the bound leading argument '#' is still passed as prefix.
Exercise
A colleague writes const Make = (name) => { this.name = name; }; and then calls new Make('Ada'). What happens, and what should they write instead?
Show answer
It throws TypeError: Make is not a constructor, because arrow functions cannot be used with new and have no this of their own. They should use function Make(name) { this.name = name; } or class Make { constructor(name) { this.name = name; } }.
Exercise
Write a constructor function Temperature(celsius) that works the same whether it is called with or without new, and returns an object with a celsius property linked to Temperature.prototype.
Show answer
function Temperature(celsius) { if (!new.target) return new Temperature(celsius); this.celsius = celsius; } Without new, new.target is undefined, so the function calls itself with new. Both new Temperature(20) and Temperature(20) return an instance where instanceof Temperature is true.