Math.round is not a constructor

Consider the following:

x = function () {}
p = new x()
console.log(p) // ok

Math.z = function () {}
p = new Math.z()
console.log(p) // ok 

p = new Math.round()
console.log(p) // TypeError: function round() { [native code] } is not a constructor

Therefore, I can use newwith my own functions, but not with Math.round. What makes it so special? Is it documented anywhere?

+3
source share
3 answers

Nothing special in Math.roundyou can reproduce this behavior in your own functions:

MyClass = function(){};
MyClass.round = function(x){ 
    if(this instanceof MyClass.round)
        throw 'TypeError: MyClass.round is not a constructor';
    return Math.round(x);
}

console.log(MyClass.round(0.5));  // 1
new MyClass.round(); // 'TypeError: MyClass.round is not a constructor'

In fact, you can use a similar pattern to make the keyword newoptional for your class:

function MyClass(){
    if(!(this instanceof MyClass)) // If not using new
        return new MyClass();      // Create a new instance and return it

    // Do normal constructor stuff
    this.x = 5;
}

(new MyClass()).x === MyClass().x;

As for why it newdoes not work with built-in functions and methods, this is by design and documented:

, , , [[Construct]], . - http://es5.github.com/#x15

+8

, new .

:

new alert()        //TypeError: Illegal invocation
new console.log()  //TypeError: Illegal invocation
new function(){}   //OK
+2

Math is a class, so you can create an object from it. Math.round is a math method. You cannot create an object from a method.

+1
source

All Articles