将方法添加到数字引发异常

Add a method to Number throws exception

本文关键字:异常 数字 方法 添加      更新时间:2023-09-26

我正在阅读javascript的优点部分,并正在测试代码。

Number.method('integer', function ( ) {
	document.writeln("called"+ this<0);
return Math[this < 0 ? 'ceiling' : 'floor'](this);
});

并通过将其调用为

document.writeln((-10 / 3).integer());

我得到Uncaught TypeError: Math[(intermediate value)(intermediate value)(intermediate value)] is not a function错误。我做错了什么吗?我正在铬上测试它

我忘了提,还有另一种方法添加到 function.protoype 作为

Function.prototype.method = function (name, func) {
 this.prototype[name] = func;
 return this;
};

没有方法Math.ceiling(),但Math.ceil()。可能这会产生错误:

未捕获的类型错误: 数学[(中间值)(中间值)(中间) 值)(中间值)] 不是函数

你需要添加到 Number 的原型中

Number.prototype.integer = function ( ) 
{
    document.writeln("called"+ this<0);
    return Math[this < 0 ? 'ceiling' : 'floor'](this);
};

添加到原型时,请确保 Number 的实例将具有此属性,而不仅仅是 Number 对象。

另外,尽量避免document.writeln因为它基本上会擦除现有文档,删除现有事件。如果需要,请使用document.body.innerHTML

Number.prototype.integer = function ( ) 
{
    document.body.innerHTML += "<br>called"+ (this<0);
    return Math[this < 0 ? 'ceil' : 'floor'](this); //observe that ceiling is also replaced with ceil since there is no such method called ceiling
};