Sub topic 10
Arrow Functions Cannot Be Constructors
This chapter assumes you know how this works in regular and arrow functions, and that you have used objects and the new keyword at least once. It explains what new needs from a function and why arrow functions don't meet those needs.
What `new` Does with a Regular Function
When you call a regular function with new, JavaScript does four things:
- It creates a new empty object.
- It sets that object's prototype to the function's
prototypeproperty. - It runs the function body with
thisbound to the new object. - It returns the new object, unless the body explicitly returns a different object.
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
return `Hi, I'm ${this.name}`;
};
const ada = new Person('Ada');
console.log(ada.greet()); // Hi, I'm Ada
console.log(Object.getPrototypeOf(ada) === Person.prototype); // trueWhy Arrows Fail Both Requirements
Steps 2 and 3 are the problem. An arrow function has no prototype property, so there is nothing to link the new object to. It also has no this of its own. It always uses the this of the surrounding scope, so the engine has no way to point this at a fresh object.
The language therefore leaves out the internal "construct" behavior from arrow functions. Calling one with new throws a TypeError before the body ever runs:
const ArrowPerson = (name) => {
this.name = name;
};
console.log(ArrowPerson.prototype); // undefined
try {
new ArrowPerson('Ada');
} catch (e) {
console.log(e instanceof TypeError); // true
console.log(e.message); // ArrowPerson is not a constructor
}You can see why by writing a simplified new by hand:
function construct(Ctor, ...args) {
const obj = Object.create(Ctor.prototype);
const result = Ctor.apply(obj, args);
const isObject =
result !== null && (typeof result === 'object' || typeof result === 'function');
return isObject ? result : obj;
}
function Point(x, y) {
this.x = x;
this.y = y;
}
console.log(construct(Point, 1, 2)); // Point { x: 1, y: 2 }
const ArrowPoint = (x, y) => ({ x, y });
try {
construct(ArrowPoint, 1, 2);
} catch (e) {
console.log(e instanceof TypeError); // true
}Object.create(undefined) throws because ArrowPoint.prototype doesn't exist. Even if it did exist, apply(obj, ...) would have no effect on the arrow's this.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Defining a constructor as an arrow | `TypeError: X is not a constructor` | Use `function` or `class` |
| Adding methods with `Arrow.prototype.m = ...` | `TypeError: Cannot set properties of undefined` | Use a class, or a regular function as the constructor |
| Using an arrow for a prototype method | `this` is the outer scope, not the instance | Use a regular function or method shorthand |
The third row catches people even when the constructor itself is correct:
function Dog(name) {
this.name = name;
}
Dog.prototype.speakArrow = () => `${this?.name} barks`;
Dog.prototype.speakRegular = function () {
return `${this.name} barks`;
};
const rex = new Dog('Rex');
console.log(rex.speakArrow()); // undefined barks
console.log(rex.speakRegular()); // Rex barksExercise
A teammate writes const Timer = (ms) => { this.ms = ms; }; and later calls Timer.prototype.start = function () {};. Which line fails first, what error is thrown, and how should Timer be rewritten?
Show answer
The line Timer.prototype.start = ... fails first with a TypeError, because Timer.prototype is undefined and you cannot set a property on undefined. Any later new Timer(1000) would also throw "Timer is not a constructor". Rewrite it as class Timer { constructor(ms) { this.ms = ms; } start() {} } or as function Timer(ms) { this.ms = ms; }.
Exercise
Without running it, predict the output of const f = () => {}; const g = function () {}; console.log(typeof f.prototype, typeof g.prototype);
Show answer
It prints "undefined object". Arrow functions have no prototype property. Regular function expressions get a prototype object automatically, so they can be used with new.