Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading