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

js code for traversing the properties of an object_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:57:451302browse

For example:

Copy code The code is as follows:

Function.prototype.addMethod=function(methodName, func){
if(!this.prototype[methodName]){
this.prototype[methodName]=func;//Add a method to the prototype, this method will affect instances of this type
}
return this.prototype;//Return prototype, this type instance can be called in a chain
}
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 |

But at this time for in also The attributes inherited by the object from the prototype object are also traversed. If you want to remove the properties it inherits, you can use the hasOwnProperty statement. For example,
Copy code The code is as follows:

Function.prototype.addMethod=function(methodName,func ){
if(!this.prototype[methodName]){
this.prototype[methodName]=func;//Add a method to the prototype, this method will affect instances of this type
}
return this.prototype;//Return prototype, this type of instance can be called in a chain
}
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 |
Statement:
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