hasOwnProperty() 方法會返回一個布爾值,指示對象自身屬性中(非繼承屬性)是否具備指定的屬性, 若是 object 具備帶指定名稱的屬性,則 hasOwnProperty 方法返回 true,不然返回 false。此方法不會檢查對象原型鏈中的屬性;該屬性必須是對象自己的一個成員。javascript
obj.hasOwnProperty(prop)
複製代碼
obj,必需。對象的實例。 prop,必需。一個屬性名稱的字符串值。html
//實例化一個對象
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= 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
複製代碼
const d = Object.prototype.hasOwnProperty('toString')
console.log(d);//true
const e = String.prototype.hasOwnProperty('split')
console.log(e);//true
複製代碼
經過for...in循環對象的全部枚舉屬性,而後再使用hasOwnProperty()方法來忽略繼承屬性。 換一種寫法java
const obj ={
name:"陌上寒",
sex:"male"
}
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(`${key}: ${obj[key]}`)
}
else
console.log(key);
}
}
複製代碼
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()prototype
hasOwnProperty 方法 (Object) (JavaScript)code