代码之家  ›  专栏  ›  技术社区  ›  Eugene Yarmash

Javascript:数字的原型

  •  3
  • Eugene Yarmash  · 技术社区  · 15 年前
    var x= 1;  
    Number.prototype.test = function () { return this };  
    x.test() === x.test() // false  
    

    为什么 === 测试返回错误?

    3 回复  |  直到 15 年前
        1
  •  3
  •   Andy E    15 年前

    因为 this

    {"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()));
    

    如果你想找个解决办法,那就投吧 到一个数字

    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()));
    
        2
  •  1
  •   vava    15 年前

    每次你打电话 .test() 创建了一个新的Number实例,这是一个非常令人期待的行为,每个装箱解决方案都是这样工作的。你可以在C#和Java中尝试同样的方法,得到完全相同的结果(好吧,Java有一个整数对象池,用于处理较小的数字,所以不会得到完全相同的结果)

        3
  •  0
  •   fglez    12 年前

    当我们在检查 ===

    在这里,问题可能是因为不同的对象创建。