【1】正常使用 hasOwnProperty()
判断对象中是否有某个属性
let o = {
name: '张三'
}
let result = o.hasOwnProperty('name')
console.log('result---', result) // true
【2】对象中有 hasOwnProperty 属性时,使用 hasOwnProperty()
判断对象中是否有某个属性
let oo = {
hasOwnProperty: '789',
name: '李四'
}
// console.log('oo.hasOwnProperty("name")----', oo.hasOwnProperty('name')) // 此时会报错 "TypeError: obj.hasOwnProperty is not a function"
let ooo = {
hasOwnProperty: function () {
return '嘿嘿嘿'
},
name: '李四'
}
console.log('ooo.hasOwnProperty("name")----', ooo.hasOwnProperty('name')) // true
console.log('ooo.hasOwnProperty("hasOwnProperty")----', ooo.hasOwnProperty('hasOwnProperty')) // 打印出 嘿嘿嘿【不是想要的结果】 --- 此时其实是调用了 ooo 对象中的 hasOwnProperty 属性,而不是使用 hasOwnProperty() 方法判断 ooo 对象中有无 hasOwnProperty 属性
【注意】
/**
* 【注意】由于 javascript 没有将 hasOwnProperty 规定为敏感词,
* 我们给对象属性命名时可能会命名为 hasOwnProperty,
* 此时就不能用上述办法判断当前对象中有没有 以 hasOwnProperty 为属性名的属性
* 采用 Object.hasOwnProperty.call(对象, '属性名') 的方法来判断对象中是否有 hasOwnProperty 属性
* 或 ({}).hasOwnProperty.call(对象, '属性名');
* 或 Object.prototype.hasOwnProperty.call(对象, '属性名'); // true
*/
let obj = {
hasOwnProperty: function () {
return '哈哈哈'
},
name: '李四'
}
console.log(
'Object.hasOwnProperty.call(obj, "name")----',
Object.hasOwnProperty.call(obj, 'name')
) // true
console.log(
'Object.hasOwnProperty.call(obj, "hasOwnProperty")----',
Object.hasOwnProperty.call(obj, 'hasOwnProperty')
) // true
本文含有隐藏内容,请 开通VIP 后查看