Javascript 创建具有自己属性的新号码

Javascript Create new Number wıth own properties

我想用 Number 的属性创建新的数字对象。 但是当为我的变量分配一个数字值时,我的变量变成了数字(原始包装对象)。并且失去了自己 properties.How 我可以防止这种情况发生吗? 例子

class Fnumber extends Number {
  value = 0;
  [Symbol.toPrimitive](hint) {
    if (hint === 'object') {
      return this;
    }
    return this.value;
  };
  //I don't want use Number.prototype.add method because this effect all Number values.
  add = function(...v) {
    this.value += Array.prototype.slice.call(arguments).reduce((o, v) => o + v)
  }
}
var nmbr = new Fnumber();
nmbr.add(4, 2, 4);
console.log(nmbr); //return a Object
console.log(nmbr + 4); //return 14 is number
nmbr = 14;
console.log(nmbr); //return not a Object its Primative number value
console.log(nmbr + 4); //return 14 a number
nmbr.add(4, 2, 4); //raise error.

在执行 nmbr = 14 时,您将 14 分配给 nmbr,您并没有更改 nmbr.value,而是覆盖了对象。而是调用 add 并在需要时使用 nmbr.value

class Fnumber extends Number {
  value = 0;

  add(...v) {
    this.value += Array.prototype.slice.call(arguments).reduce((o, v) => o + v)
  }
}
var nmbr = new Fnumber();
nmbr.add(4, 2, 4);
console.log(nmbr.value);
nmbr.add(5);
console.log(nmbr.value);

nmbr.value = 25; // assign a value to nmbr.value
console.log(nmbr.value);

如果您不打算重新分配对象,一个好的做法是使用 const 而不是 var,请参阅下面的错误。

class Fnumber extends Number {};
const nmbr = new Fnumber();
nmbr = 14;

我间接找到了解决方案。

class Fnumber extends Number {
value = 0;
add(...v) {
   this.value += Array.prototype.slice.call(arguments).reduce((o, v) => o + v)
}
}
//temğrary variable description
var _nmbr=new Fnumber();
//Define nmbr variable in global scobe
Object.defineProperty(window,"nmbr",{
    enumerable: true,
    configurable: true,
    get() { return _nmbr; },
    set(val) { if (typeof val=="number")_nmbr.value=val; }
});
nmbr=4;
console.log(nmbr+2);//output 6
//still nmbr variable is object,because assigned value  to 
_nmbr.value with above set method
nmbr.add(4, 2, 4);
console.log(nmbr+2);//output 16