2017-04-27 20 views
0

我想在我的HTML页面的脚本标签使用下面的代码来增强的JavaScript的内置Number数据类型:错误,而试图以增强内置类型的JavaScript

Number.method('integer', function() { 
     return Math[this < 0 ? 'ceiling' : 'floor'](this); 
     }); 
     document.writeln((-10/3).integer()); 

当我在浏览器的页面,然后开发人员工具报告的后续错误:

Uncaught TypeError: Number.method is not a function
at test.html:10 (anonymous) @ test.html:10

浏览器信息:谷歌浏览器

我无法识别我的代码中的错误。有人能帮助我吗?

+0

没有人必须使用'原型'的内置“对象”? – Pyromonk

+0

我已经尝试过这个选项,但是这个错误只是变成了'未捕获的TypeError:Number.prototype.method不是一个函数' – RBT

+0

这个主题有帮助吗? http://stackoverflow.com/questions/27035308/add-a-rounding-method-to-number-prototype-in​​-javascript – Pyromonk

回答

1

是的,您必须定义method,并使用ceil而不是ceiling

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

 
Number.method('integer', function() { 
 
    return Math[this < 0 ? 'ceil' : 'floor'](this); 
 
}); 
 

 
console.log((-10/3).integer());

当然,在这种特殊情况下,你也只是做number | 0

+0

谢谢。我错过了为'Function'的原型添加'method'扩展。 '天花板'是我相信目前我所指的书本身的印刷错误。接得好! – RBT