JS中的hasOwnProperty()、propertyIsEnumerable()和isPrototypeOf()

(编辑:jimmy 日期: 2024/10/3 浏览:2)

首先了解枚举属性

一般利用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遍历中可枚举的属性。

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():每个对象都有,表示当前对象是否是另一个对象的原型

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(),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

一句话新闻

高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。