如: 复制代码 代码如下: 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 |
推荐阅读
jQuery中创建实例与原型继承揭秘
如 new Object()、new Date()等等!(object有{},数组有[]这样的快捷方式 ,我们主要探讨new这种方式。) 我们在使用jQuery时从来没有使用过new,他是不是用其他方法来生成实例呢?是不是没有使用prototype属性呢>>>详细阅读
本文标题:js 遍历对象的属性的代码
地址:http://www.17bianji.com/kaifa2/JS/23783.html
1/2 1