Search code examples
javascriptobjectprimitive

The inheritance of javascript


Maybe this question is easy,but I can't understand now.

String.prototype.self=function()
{
    return this;
}
var s="s";

alert("s".self()=="s".self()) //false;
alert(s.self()==s.self()) //false;

If you know the reason, please tell me why the result is "false".


Solution

  • That's because when a property is accessed from a primitive value, such as "s", the property accesors coerce it internally ToObject, and the comparison fails because it checks two different object references.

    For example:

    String.prototype.test = function() {
      return typeof this;
    }
    
    "s".test(); // "object"
    

    It's like comparing:

    new String("s") == new String("s"); // false