首先了解枚举属性
一般利用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(),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
P70系列延期,华为新旗舰将在下月发布
3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。
而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?
根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。