Javascript:数字的原型(prototype)

标签 javascript prototype numbers

var x= 1;  
Number.prototype.test = function () { return this };  
x.test() === x.test() // false  

为什么 === 测试返回 false?

最佳答案

因为 this 将是一个 Number 对象,而不是原始原始数字值,比较两个同样创建的对象将始终返回 false:

{"test":"Hello"} === {"test":"Hello"} // false

// Check the typeof your vars
var x= 1;  
Number.prototype.test = function () { return this };  
x.test() === x.test() // false 
alert("x is a "+typeof(x)+", x.test() is an "+typeof(x.test()));

如果您正在寻找修复方法,请将 this 转换为数字

var x= 1;  
Number.prototype.test = function () { return +this };  
x.test() === x.test() // TRUE!
alert("x is a "+typeof(x)+", x.test() is also a "+typeof(x.test()));

关于Javascript:数字的原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2400689/

相关文章:

javascript - NestJS - 如何在主应用程序模块文件中使用 .env 变量进行数据库连接

javascript - Chrome使用jquery时出现问题

javascript - 如何在 JavaScript 中将输入括号与正则表达式匹配?

javascript - 多个 Element.prototype 不起作用

c# - 为随机和不重复创建数字

asp.net-mvc - 该字段必须是数字。如何将此消息更改为另一种语言?

Javascript(纯)选择第一个元素(表)

jquery - Rails Ajax 使用 RJS 隐藏/显示切换链接

c++ - 数组/指针/引用混淆

java - 对于没有无参数构造函数的类,应该如何扩展 Number?