扩展 Number 得到一个自然数

Extending Number to get a natural number

读完 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

有什么想法吗?

你可以这样使用它:

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());

当你说 "error" 我假设你的意思是 "incorrect result"。

问题是 -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=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