javascript查看对象拥有的属性
Object.prototype.properties = function(){
var result = [];
for (var property in this)
result.push(property);
return result;
}
var test = {a: 10, b:3};
test.properties();
//这并不是我们想要的结果,这个将Object原型中的一个属性都拿出来了
//["a", "b", "properties"]
Object.prototype.properties = function(){
var result = [];
for(var property in this){
if(this.hasOwnProperty(property)){
result.push(property);
}
}
return result;
}
//["a", "b"]
根本原因就是使用for/in会将原型中的属性拿出来,而真正取出对象属性的是对象本身的一个方法hasOwnProperty
,返回给定对象的所有属性