Math.round不是构造函数

时间:2012-05-07 06:51:48

标签: javascript

请考虑以下事项:

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

所以我可以将new与我自己的函数一起使用,但不能与Math.round一起使用。是什么让它如此特别?这是在某处记录的吗?

3 个答案:

答案 0 :(得分:8)

Math.round没什么特别的。你可以在自己的函数上复制这个行为:

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'

事实上,您可以使用类似的模式在您的班级中将new关键字设为可选:

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;

至于为什么new不能与内置函数和方法一起使用,这是设计和记录的:

  

除非在特定函数的描述中另有规定,否则本节中描述的非构造函数的内置函数都不应实现[[Construct]]内部方法。 - http://es5.github.com/#x15

答案 1 :(得分:2)

这是一种方法,这就是为什么你不能把new放在它之前。

PS:

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

答案 2 :(得分:1)

Math是一个类,因此您可以从中创建一个对象。 Math.round是一种数学方法。您无法从方法创建对象。

相关问题