深入解析JavaScript中的hasOwnProperty、propertyIsEnumerable与isPrototypeOf方法
本文详细解析JavaScript中判断对象属性的三个核心方法:hasOwnProperty、propertyIsEnumerable和isPrototypeOf。通过对比for-in遍历行为,阐明如何区分自身属性与原型属性,识别可枚举性,并验证原型关系,帮助开发者精准控制属性访问与遍历逻辑。
理解JavaScript中的枚举属性
首先明确枚举属性的概念
通常采用for~in循环进行遍历
var a = [1,2,3];
for(var i in a){
console.log(a[i]);
}
or
var o = {p1:1,p2:2};
for(var i in o){
console.log(i+'='+o[i]);
}//p1=1;p2=2;
<1>并非所有属性都会出现在for~in遍历结果中,例如数组的length属性及constructor属性。已显示的属性称为可枚举属性,可利用各对象提供的propertyIsEnumerable()方法甄别可枚举属性;
<2>原型链上的属性若具备可枚举性亦会显示,利用hasOwnProperty()可判定属性归属自身还是原型;
<3>针对所有原型属性,propertyIsEnumerable()均返回false,即便该属性在for~in遍历中可枚举。
使用propertyIsEnumerable判断可枚举性
js代码示例
function dog(name,color){
this.name = name;
this.color = color;
this.someMethod = function(){return 1;}
}
dog.prototype.price=100;
dog.prototype.rating=3;
var newDog = new dog("doggg","yellow");
for(var prop in newDog){
console.log(prop+'='+newDog[prop]);
}
//name=doggg
//color=yellow
//someMethod=function (){return 1;}
//price=100
//rating=3
newDog.hasOwnProperty('name');//true;
newDog.hasOwnProperty('price');//false;
仅展示自身属性
for(var prop in newDog){
if(newDog.hasOwnProperty(prop )){
console.log(prop+'='+newDog[prop]);
}
}
newDog.propertyIsEnumerable('name');//true
newDog.propertyIsEnumerable('constructor');//false
注意:内置属性与方法大多不可枚举
源自原型链的属性同样不可枚举
若propertyIsEnumerable()调用源自原型链对象,则该对象属性为可枚举
newDog.constructor.prototype.propertyIsEnumerable('price');//true
利用isPrototypeOf验证原型关系
isPrototypeOf():所有对象均具备,指示当前对象是否为另一对象的原型
js代码示例
var monkey = {
hair:true,
feeds:'bananas',
breathes:'air'
};
function Human(name){
this.name = name;
}
Human.prototype = monkey;
var george = new Human('George');
monkey.isPrototypeOf(george);//true
上述内容为小编整理的JS中hasOwnProperty()、propertyIsEnumerable()及isPrototypeOf()相关知识,望对大家有所助益。如有任何疑问请留言,小编将及时回复。衷心感谢各位对本网站的支持!
JS中将数组和对象混合组装为JSON字符串
2026-11-05 16:41:42
JS运算符优先级与结合性的区别是什么?
2026-11-05 13:22:02
JS Map怎么只遍历Key或Value
2026-11-05 13:00:36
D3.js 与 ECharts 选型对比:灵活性 vs 开发效率
2026-11-05 09:45:01
为什么JS中typeof []返回object:数组类型检测误区解析
2026-11-04 19:50:47
