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方法的
时候却用上了这个方法?
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。