3

考虑以下:

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. 是什么让它如此特别?这是在某处记录的吗?

4

3 回答 3

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

于 2012-05-07T07:01:51.793 回答
2

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

ps:

new alert()        //TypeError: Illegal invocation
new console.log()  //TypeError: Illegal invocation
new function(){}   //OK
于 2012-05-07T06:58:16.270 回答
1

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

于 2012-05-07T06:58:07.660 回答