Javascript 扩展数以获得自然数
在阅读了Crockford的JavaScript之后,我非常感兴趣:做这件事的好部分:Javascript 扩展数以获得自然数,javascript,numbers,prototype,Javascript,Numbers,Prototype,在阅读了Crockford的JavaScript之后,我非常感兴趣:做这件事的好部分: Function.prototype.method=function(name, func){ this.prototype[name] = func; return this } 我可以扩展数字,这样就可以: Number.method('integer',function(){ return Math.round(this) }); 44.4.整数()//44 但当尝试获取正整数(自然数)
Function.prototype.method=function(name, func){
this.prototype[name] = func;
return this
}
我可以扩展数字,这样就可以:
Number.method('integer',function(){
return Math.round(this)
});
44.4.整数()//44
但当尝试获取正整数(自然数)时,会抛出错误:
Function.prototype.method=function(name, func){
this.prototype[name] = func;
return this
}
Number.method('natural',function(){
return Math.round(Math.abs(this))
});
-44.4.natural();// error or doesn't work
有什么想法吗?你可以这样使用它:
console.log((-44.4).natural());
您的问题是44.4.natural()首先被执行,然后打印其负片
Function.prototype.method=函数(名称,func){
this.prototype[name]=func;
还这个
}
Number.method('natural',function(){
返回Math.round(Math.abs(this))
});
console.log(-44.4.natural())代码>当你说“错误”时,我想你的意思是“结果不正确”
问题是-44.4.natural()
实际上是-(44.4.natural())
。如果在natural
方法中查看this
,您会发现它是44.4
,而不是-44.4
JavaScript没有负数文本格式。它使用否定运算符。优先规则意味着先进行方法调用,然后进行否定
如果要使用-44.4
作为值,请将其放入变量中:
let a = -44.4;
console.log(a.natural()); // 44.4
实例:
Function.prototype.method=函数(名称,func){
this.prototype[name]=func;
还这个
}
Number.method('natural',function(){
return Math.abs(这个)
});
设a=-44.4;
console.log(a.natural())代码>