Andrei Zhamoida Andrei Zhamoida - 17 days ago 5
Javascript Question

Math isn't a constructor but it has

Here's a trick question i can't figure out. As I read from MDN we cannot create instance from

Math
. Running
new Math()
will produce an exception
Math is not a constructor
. But Math has own property inside
Math.constructor
. Yes it's
Object
type but we could run it
Math.constructor()
. But even we redefine it by exec
Math.constructor = Function.constructor
it also throw an exception.

Now I had some suppositions in my mind:


  • constructor contains a hidden property and browser engine refuses invoke it.

  • constructor interpreted into special c++ object in browser engine which has index in "TypeError:not a constructor" collection.



Could someone answer me thoroughly why constructor exists but I cannot create an instance?

Thanks in advance.

Answer

To quote myself, the answer is

because the spec says so

and the spec says

The Math Object

The Math object is a single object that has some named properties, some of which are functions.

The value of the [[Prototype]] internal property of the Math object is the standard built-in Object prototype object (15.2.4). The value of the [[Class]] internal property of the Math object is "Math".

The Math object does not have a [[Construct]] internal property; it is not possible to use the Math object as a constructor with the new operator.

The Math object does not have a [[Call]] internal property; it is not possible to invoke the Math object as a function.

Every object in javascript has a constructor, and Math is an object, hence it has a constructor, that doesn't mean you can create new instances of it, it's the same as

var Math = {
  random : true,
  max    : false
}

new Math(); // epic fail, not a constructor (function)