JavaScript中如何进行属性检测

JavaScript对象可以看做是属性的集合,为了容错处理、健壮性等目的,我们经常会判断它是否存在某个属性。常用的有这几种方法:in, hasOwnProperty(), propertyIsEnumerable(),属性查询。

in

var o = {x:1};
"x"  in o;                 // true
"y"  in o;                 // false
"toString"  in o;          // true:o继承toString属性

hasOwnProperty()

检测是否含有自有属性

 var o = {x:1};
 o.hasOwnProperty("x");    // true
 o.hasOwnProperty("y");    // false
 o.hasOwnProperty("x");    // true:o继承toString属性,而不是自有属性

propertyIsEnumerable()

是hasOwnProperty()的增强版,检测是否含有自有属性并且属性是可枚举的(enumerable attribute 为true)

 var o = inherit({y:2})
 o.x = 1;
 o.propertyIsEnumerable("x")    // true
 o.propertyIsEnumerable("y")    // false:y是继承的
 Object.prototype.propertyIsEnumerable("toString"); // false:不可枚举
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容