如:
function.prototype.addmethod=function(methodname,func){
if(!this.prototype[methodname]){
this.prototype[methodname]=func;//给原型增加方法,此方法会影响到该类型的实例上
}
return this.prototype;//返回原型,此类型实例可以进行链形调用
}
function customobject(name,value){
this.name=name || 'customeobject';
this.value=value || 0;
this.tostring=function(){
return '[name:'+this.name+',value:'+this.value+']'
}
}
customobject.addmethod('testfun',function(){})
var obj=new customobject();
var info='';
for(var property in obj){
info+=property+" | ";
}
alert(info); // name | value | tostring | testfun |
但此时for in 也把该对象所继承于prototype对象中的属性也遍历出来了。如果要剔除它所继承的属性,可以用hasownproperty语句。如
function.prototype.addmethod=function(methodname,func){
if(!this.prototype[methodname]){
this.prototype[methodname]=func;//给原型增加方法,此方法会影响到该类型的实例上
}
return this.prototype;//返回原型,此类型实例可以进行链形调用
}
function customobject(name,value){
this.name=name || 'customeobject';
this.value=value || 0;
this.tostring=function(){
return '[name:'+this.name+',value:'+this.value+']'
}
}
customobject.addmethod('testfun',function(){})
var obj=new customobject();
var info='';
for(var property in obj){
if(!obj.hasownproperty(property)) continue;
info+=property+" | ";
}
alert(info); // name | value | tostring |
更多js 遍历对象的属性的代码。