Javascript using prototype how can I set the value of “this” for a number?

前端 未结 3 1985
执笔经年
执笔经年 2021-01-27 16:09

So if we can get past the \"should you?\" question ... does anyone know how to set the value of an integer in prototype?

相关标签:
3条回答
  • 2021-01-27 16:20

    JavaScript has both number primitives and Number objects. Number primitives are immutable (like all primitives in JavaScript). The numeric value of a Number object is also immutable. So your add method can only return the updated value. You can create your own number-like object, of course, with a mutable value.

    Details about number immutability and your own number object in this other answer (didn't realize that question was a duplicate when answering it).

    0 讨论(0)
  • 2021-01-27 16:29

    Number.prototype.add = function(num){
      var newVal = this.valueOf() + num;
      this.valueOf(newVal);
      return newVal;
    }
    
    var rad = new Number(4001.23);
    document.write(rad.add(10) + '<br/>' + rad);

    0 讨论(0)
  • 2021-01-27 16:33

    Essentially you cant, Numbers, Booleans and Strings are immutable

    0 讨论(0)
提交回复
热议问题