Home > Web Front-end > JS Tutorial > js code for traversing the properties of an object

js code for traversing the properties of an object

高洛峰
Release: 2017-01-14 11:16:16
Original
1809 people have browsed it

For example:

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 |
Copy after login

But at this time for in also traverses the attributes inherited by the object from the prototype object. If you want to remove the properties it inherits, you can use the hasOwnProperty statement. Such as

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 |
Copy after login

For more js code related articles for traversing the properties of objects, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template