开发者

The inheritance of javascript

开发者 https://www.devze.com 2023-01-07 06:06 出处:网络
Maybe this question is easy,but I can\'t understand now. String.prototype.self=function() { return this;

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".


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号