Home > Web Front-end > JS Tutorial > body text

js 遍历对象的属性的代码_javascript技巧

WBOY
Release: 2016-05-16 17:57:45
Original
1235 people have browsed it

如:

复制代码 代码如下:

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 |
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!