您的位置:首页 > Web前端 > JavaScript

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

2016-08-11 10:17 751 查看

首先了解枚举属性

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

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息