javascript的Object. hasOwnProperty方法

摘要:hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中(非继承属性)是否具有指定的属性,如果 object 具有带指定名称的属性,则 hasOwnProperty 方法返回 true,否则返回 false。

hasOwnProperty基本概念

hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中(非继承属性)是否具有指定的属性,
如果 object 具有带指定名称的属性,则 hasOwnProperty 方法返回 true,否则返回 false。此方法不会检查对象原型链中的属性;该属性必须是对象本身的一个成员。


使用语法

obj.hasOwnProperty(prop)


参数

obj,必需。对象的实例。
prop,必需。一个属性名称的字符串值。


demo

判断自身属性是否存在

//实例化一个对象
const obj = new Object();
//为obj添加属性name
obj.name = "陌上寒";
//为obj添加属性sex
obj.sex="male"

const a = obj.hasOwnProperty('name');
console.log(a);// true
//删除obj的name属性
delete obj.name
const b = obj.hasOwnProperty('name');
console.log(b); // false
const c = obj.hasOwnProperty('sex');
console.log(c); //  true


无法通过obj.hasOwnProperty(prop)判断继承属性

obj= new Object();
obj.name = '陌上寒';
const a = obj.hasOwnProperty('name');
console.log(a);//true
const b = obj.hasOwnProperty('toString');
console.log(b);//false
const c = obj.hasOwnProperty('hasOwnProperty');
console.log(c);//false

如果要判断继承属性,通过原型链prototype判断

const d = Object.prototype.hasOwnProperty('toString')
console.log(d);//true
const e = String.prototype.hasOwnProperty('split')
console.log(e);//true


遍历一个对象的所有自身属性

通过for...in循环对象的所有枚举属性,然后再使用hasOwnProperty()方法来忽略继承属性。
换一种写法

const obj ={
    name:"陌上寒",
    sex:"male"
}
for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
        console.log(`${key}: ${obj[key]}`)
    }
    else 
        console.log(key); 
    }
}


JavaScript 并没有保护 hasOwnProperty 属性名,使用起来可能会有坑

const foo = {
    hasOwnProperty: function() {
        return false;
    },
    bar: '这是一个坑,可能永远返回false'
};
const hasBar = foo.hasOwnProperty('bar'); 
console.log(hasBar);// 始终返回 false

// 如果担心这种情况,可以直接使用原型链上真正的 hasOwnProperty 方法
const a = ({}).hasOwnProperty.call(foo, 'bar'); // true
console.log(a);
// 也可以使用 Object 原型上的 hasOwnProperty 属性
const b = Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
console.log(b);


原文地址


本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_1248