hasOwnProperty,Object.keys(),propertyIsEnumerable,for-in(loop),
分享于 点击 8036 次 点评:63
hasOwnProperty,Object.keys(),propertyIsEnumerable,for-in(loop),
功能及用法:
hasOwnProperty():用来检查私有属性。若是私有属性,则返回true,否则返回false,(例如:原型对象中的属性属于继承属性,所以返回的是false)。例如:
function Fn(){
this.name="test";
}
Fn.prototype.age=123;
var temp = new Fn();
temp.hasOwnProperty("name");//true
temp.hasOwnProperty("age");//false
Object.keys():该方法返回的是对象可枚举的属性(不包括对象从原型链上继承的属性)。返回结果是个数组,数组元素就是属性名。例如:
Object.keys({name:"test",age:234});//["name","age"]
propertyIsEnumerable():用来判断对象的属性是否可以枚举,只包括私有属性,不包含原型对象中继承的属性(javascript核心对象的默认属性一般是不允许枚举的)。例如:
function Fn(){
this.a=1;
this.b=3;
}
Fn.prototype.c=3;
var o = new Fn();
o.propertyIsEnumerable("a");//true
o.propertyIsEnumerable("b");//true
o.propertyIsEnumerable("c");//false
for in:可以遍历对象中的私有属性和继承属性(原型链里的)。例如:function Fn(){
this.a=1;
this.b=3;
}
Fn.prototype.c=3;
for(var i in (new Fn())){
console.log(i);//依次输出:a,b,c
}
note:在ie6下如果在私有属性里或者原型里重新定义了Object对象的基本方法(toString(),toLocalString(),valueOf(),isPrototypeOf(),hasOwnProperty(),propertyIsEnumerable()),是覆盖不了Object里的基本方法,也就是说,你重新定义的这些不起作用。其他的浏览器可以覆盖。这儿是一篇对ie6这个问题的兼容解决方案。
相关文章
- 暂无相关文章
用户点评