判断对象是否存在某个属性
JavaScript判断对象是否存在某个属性或者方法,常用方法有两种hasOwnProperty和in
hasOwnProperty是Object原型对象上的一个方法,用来判断对象自身属性中是否具有指定的属性。
这个方法可以用来检测一个对象是否含有特定的自身属性;和 in 运算符不同,该方法会忽略掉那些从原型链上继承到的属性。
// eslint-disable-next-line no-new-object const obj = new Object(); obj.name = myObject; console.log(obj.hasOwnProperty(name)); // true console.log(obj.hasOwnProperty(toString)); // false console.log(obj.hasOwnProperty(hasOwnProperty)); // false console.log(name in obj); // true console.log(toString in obj); // true
MDN上指出,JavaScript 并没有保护 hasOwnProperty 这个属性名,可以将任意对象的一个属性命名为hasOwnProperty,这样一来就无法使用原型对象上的hasOwnProperty方法了。解决办法,直接使用原型链上的hasOwnProperty方法:
// 可以直接使用原型链上真正的 hasOwnProperty 方法
({
}).hasOwnProperty.call(obj, name); // true
// 也可以使用 Object 原型上的 hasOwnProperty 属性
Object.prototype.hasOwnProperty.call(obj, name); // true
推荐使用第二种方式。
