本文主要是介绍Object. hasOwnProperty方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
hasOwnProperty基本概念
hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中(非继承属性)是否具有指定的属性,
如果 object 具有带指定名称的属性,则 hasOwnProperty 方法返回 true,否则返回 false。此方法不会检查对象原型链中的属性;该属性必须是对象本身的一个成员。
使用语法
obj.hasOwnProperty(prop)
参数
obj,必需。对象的实例。## ** demo** 判断自身属性是否存在
prop,必需。一个属性名称的字符串值。
//实例化一个对象
const obj = new Object();
//为obj添加属性name
obj.name = "刘家军";
//为obj添加属性hobby
obj.hobby="knockCode"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('hobby');
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:"刘家军",hobby:"knockCode"
}
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()
友情链接:点击查看所有文章目录
友情链接:点击查看 JavaScript原型与原型链系列文章目录
这篇关于Object. hasOwnProperty方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!