陌上人如玉
公子世无双

关于javascript的Object. hasOwnProperty,看我就够了

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);

参考链接:
Object.prototype.hasOwnProperty()
hasOwnProperty 方法 (Object) (JavaScript)
js属性对象的hasOwnProperty方法

赞(0) 打赏
未经允许不得转载:陌上寒 » 关于javascript的Object. hasOwnProperty,看我就够了

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

微信扫一扫

支付宝扫一扫