David542
David542

Reputation: 110277

Can new be called on anything other than a class/function

Is it possible to directly modify objects so that they can be created with the new keyword, or does that only apply to functions/classes? As an example:

const bird = {
    swim() {return 'Swim';},
    fly() {return 'Fly';}
};
let b1 = Object.create(bird);

bird.constructor = function(){console.log('via constructor')};
let b2 = new bird();

There's no practical use of this, I'm more just learning things and seeing how new works and such.

Upvotes: 0

Views: 24

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370879

No.

Using new results in EvaluateNew being called, which does

  1. If IsConstructor(constructor) is false, throw a TypeError exception.

which does

  1. If argument has a [[Construct]] internal method, return true.

and that internal property is only permitted on functions:

A constructor is an object that supports the [[Construct]] internal method. Every object that supports [[Construct]] must support [[Call]]; that is, every constructor must be a function object.

Upvotes: 2

Related Questions