Reputation: 110277
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
Reputation: 370879
No.
Using new
results in EvaluateNew
being called, which does
- If IsConstructor(constructor) is false, throw a TypeError exception.
which does
- 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