打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
看犀牛书小结(2)
function GenericToString(x,y){
     this.x = x;
     this.y = y;
     this.getX = function(){return this.x;}
     this.getY = function(){return this.y;}
}
 
GenericToString.prototype.toString = function(){
var props = [];
for(var name in this){
if(!this.hasOwnProperty(name))continue;
var value = this[name];
var s = name + ":";
switch(typeof value){
    case 'function':
    s+="function";
    break;
case 'object':
    if(value instanceof Array) s+="Array";
    else s+value.toString();
    break;
default:
    s+=String(value);
    break;
}
props.push(s);
}
return "(" + props.join(", ") + ")";
}
 
GenericToString.prototype.equals = function(that){
    if(this == that) return true;
    var propsInThat = 0;
    for(var name in that){
        propsInThat++;
        if(this[name] != that[name]) return false;
    }
 
    var propsInThis = 0;
    for(name in this) propsInThis++;
    if(propsInThat != propsInThis) return false;
   
    return true;
}
 
var g = new GenericToString(1,2);
for(var gname in g){
    if(!g.hasOwnProperty(gname)){
        document.write(gname + "<br>");   
    }
}
document.write("toString方法-->"+g.toString());
 
上面的输出结果是:
equals
toString方法-->(x:1, y:2, getX:function, getY:function)
 
疑问:GenericToString对象的原型prototype里面不是有toString方法和equals方法的?
怎么用hasOwnProperty()方法的时候toString()方法却不在里面,但是用对象调用toString方法的
时候却用上了这个方法?
 
 
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
从JavaScript 数组去重谈性能优化
Object 对象
JS基础知识理解之一: 原型链
原型-尽人事以听天命
JS hasOwnProperty()方法检测一个属性是否是对象的自有属性的方法
五分钟刷新一次页面
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服