如:
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 遍歷物件的屬性的程式碼相關文章請關注PHP中文網!