第30节 检测和枚举属性-Javascript-零点程序员-王唯

本内容是《Web前端开发之Javascript视频》的课件 , 请配合大师哥《Javascript》视频课程学习 。
【第30节 检测和枚举属性-Javascript-零点程序员-王唯】检测属性:
ES对象可以看作是属性的集合 , 在实际场景中 , 会经常检测集合中成员的所属关系 , 比如 , 判断某个属性是否存在于某个对象中;可以通过in运算符、hasOwnProperty和propertyIsEnumerable方法来完成 , 甚至仅通过属性可以做到;
hasOwnProperty()方法:可以检测一个属性是存在于实例中 , 还是存在于原型中;即给定属性存在于对象实例中 , 才会返回true , 继承属性返回false , 如:
varp1=newPerson();varp2=newPerson();alert(p1.hasOwnProperty("name"));//falsep1.name="wujing";alert(p1.hasOwnProperty("name"));//truedeletep1.name;alert(p1.name);//wangweialert(p1.hasOwnProperty("name"));//falsepropertyIsEnumerable()是hasOwnProperty的增强版 , 只有检测到是实例属性且这个属性是可枚举的它才返回true;如:
varo={x:1};varobj=Object.create(o);obj.y=1;console.log(o.propertyIsEnumerable("x"));trueconsole.log(obj.propertyIsEnumerable("x"));trueconsole.log(obj.propertyIsEnumerable("y"));trueconsole.log(Object.prototype.propertyIsEnumerable("toString"));//false , 不可枚举in操作符:
in操作符会通过对象能够访问给定属性时返回true , 无论属性存在于实例中还是原型中:
alert(p1.hasOwnProperty("name"));//falsealert("name"inp1);//true除了in操作符 , 更为便捷的方式是使用“!==”判断一个属性是否是undefined , 如:
varo={x:1};o.x!==undefined;//trueo.y!==undefined;//falseo.toString!=undefined;//true,o继承了toString有一种场景只能使用in而不能使用上述属性访问的方式 , in可以区分该属性存在但值为undefined的情景 , 如:
varo={x:undefined};o.x!==undefined//false,属性存在 , 但值为undefinedo.y!==undefined//false , 属性不存在"x"ino;//true,属性存在"y"ino;//flase,属性不存在deleteo.x;"x"ino;//false在使用”!==”时 , 要注意其与“!=”不同点 , “!==”可以区分undefined和null , 如:
varo={x:2};//如果o中存在属性x,且x的值不是null或undefined , 则o.x乘以2if(o.x!=null)o.x*=2;//如果o中存在属性x , 且x的值不能转换为false , o.x乘以2//如果x是undefined、null、false、“”、0或NaN , 则它保持不变if(o.x)o.x*=2;同时使用hasOwnProperty()方法和in操作符 , 可以确定该属性是存在于对象还是原型中;
//判断是否为原型varp1=newPerson();//p1.name="wujing";//添加此名就会返回falsefunctionhasPrototypeProperty(object,name){return!object.hasOwnProperty(name)&&(nameinobject);}alert(hasPrototypeProperty(p1,"name"));//true//或者:varobj={name:"wang",age:100,sex:'male',__proto__:{lastName:"wei


    推荐阅读