javascript - 在 javascript 原型(prototype)中使用 valueOf 函数

标签 javascript

我在阅读有关 javascript 原型(prototype)的文章时,发现了以下代码,它扩展了 Number 类以添加一个显示对象类型的函数

Number.prototype.toString = function() {
    return typeof (this);
}
(123).toString(); //prints "object"

我读到可以使用 valueOf 函数获得原始表示

 n = new Number(123);
 typeof n.valueOf() // prints "number"

所以我尝试在 toString 函数中获取 premitive 表示,例如

Number.prototype.toString = function() {
    return typeof (this.valueOf());
}
(123).toString(); //prints "object"

我期待它返回 "number",但它打印了 "object"。这是预期的行为还是我错过了介于两者之间的某些东西?

更新:Firebug 和 chrome 控制台为我打印“对象”并且警报在两种情况下都显示数字 UPDATE2:这是一个错误。 console.log((123).toString()) 打印数字

最佳答案

我无法让它打印除“数字”以外的任何内容。即使您专门从一个数字创建一个 Object,它也会变成一个数字。

(我将方法命名为 getType 以避免与现有的 toString 方法发生任何冲突。不过,我使用 toString 得到了相同的结果。 )

Number.prototype.getType = function() {
    return typeof this.valueOf();
}
console.log((123).getType()); // prints "number"

var n = 123;
console.log(n.getType()); // prints "number"

var o = new Number(123);
console.log(o.getType()); // prints "number"

var x = new Object(123);
console.log(x.getType()); // prints "number"

我已经在 IE(10、9、8、7)、Firefox 和 Chrome 中对此进行了测试,并得到了相同的结果。

测试:http://jsfiddle.net/Guffa/Xc7TC/

关于javascript - 在 javascript 原型(prototype)中使用 valueOf 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15780496/

相关文章:

javascript - setMinutes 未得到预期结果

javascript - 为什么 node.js 不使用 guerrillamail 生成电子邮件?

javascript - 操纵 Dom 元素

javascript - Fullcalendar - 拖动多个外部事件 - 结果代表日历上的 1 个事件

javascript - 如何同时设置href和title属性并给它一个回调函数?

javascript - 我该如何修复 - 未捕获的类型错误 : Cannot read property 'scrollHeight' of undefined

javascript - 将字符串日期转换为 JavaScript 日期

javascript - 如何在创建新对象时应用条件检查并执行代码?

javascript - 带有输入元素的AngularJS自定义指令,从外部传递验证器

javascript - Angular : filter and bold part of the result