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

首先了解枚举属性
一般利用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiaobangsky

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值