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