使用原型(prototype)的Javascript如何设置数字的值 "this"?

标签 javascript numbers set prototype

那么,如果我们能够克服“你应该吗?”的问题。问题...有人知道如何在原型(prototype)中设置整数的值吗?

Number.prototype.add = function(num){
  var newVal = this.valueOf() + num;
  this.valueOf(newVal);
  return newVal;
}

var rad = 4001.23;
document.write(rad.add(10) + '<br/>' + rad);

你会注意到 rad.add(10) 返回变量“rad”中包含的数字加 10,但我真的很想从原型(prototype) add 函数中更改 rad 的值(我知道 this.valueOf (newVal)没有完成)。

这可以做到吗?如果是这样,怎么办?

最佳答案

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

关于使用原型(prototype)的Javascript如何设置数字的值 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26130463/

相关文章:

java - 寻找 java.util.Set 的无界、基于队列的并发实现

javascript - d3js : Apply animation together on bubbles and texts

javascript - Webaudio 振​​荡器启动()回调?

javascript - react : Make flash message disappear automatically

replace - 使用Notepad++将数字替换为某种格式

带有 Set 的 Haskell Ord 实例

Python .sort() 对集合列表返回 None

javascript - Google Maps API - 类 GLatLngBounds 的问题

php - 在 PHP 中显示带序号后缀的数字

html - 为什么我不应该对 TD(表格单元格)上的数字使用已弃用的对齐 ='right'?