扩展数字以获得自然数

问题描述 投票:4回答:2

在阅读Crockford的JavaScript之后,我非常感兴趣:好的部分,这样做:

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

我可以扩展Number,所以这可以工作:

Number.method('integer',function(){
  return Math.round(this)
});

44.4.integer(); // 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

有任何想法吗?

javascript numbers prototype
2个回答
2
投票

你可以像这样使用它:

console.log((-44.4).natural());

你的问题是44.4.natural()首先执行,然后你打印出负面的。

    Function.prototype.method=function(name, func){
      this.prototype[name] = func;
      return this
    }
    Number.method('natural',function(){
      return Math.round(Math.abs(this))
    });
    
    console.log((-44.4).natural());

1
投票

当你说“错误”时,我认为你的意思是“错误的结果”。

问题是-44.4.natural()实际上是-(44.4.natural())。如果你看看this方法中的natural,你会发现它是44.4,而不是-44.4

JavaScript没有负数字格式。它使用了否定运算符。优先规则意味着首先完成方法调用,然后是否定。

如果您想使用-44.4作为您的值,请将其放在变量中:

let a = -44.4;
console.log(a.natural()); // 44.4

实例:

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

Number.method('natural',function(){
  return Math.abs(this)
});

let a = -44.4;
console.log(a.natural());

或使用()

console.log((-44.4).natural()); // 44.4

实例:

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

Number.method('natural',function(){
  return Math.abs(this)
});

console.log((-44.4).natural()); // 44.4
© www.soinside.com 2019 - 2024. All rights reserved.