關於javascript的Object. hasOwnProperty,看我就夠了

hasOwnProperty基本概念

hasOwnProperty() 方法會返回一個布爾值,指示對象自身屬性中(非繼承屬性)是否具備指定的屬性, 若是 object 具備帶指定名稱的屬性,則 hasOwnProperty 方法返回 true,不然返回 false。此方法不會檢查對象原型鏈中的屬性;該屬性必須是對象自己的一個成員。javascript

使用語法

obj.hasOwnProperty(prop)
複製代碼

參數

obj,必需。對象的實例。 prop,必需。一個屬性名稱的字符串值。html

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()方法來忽略繼承屬性。 換一種寫法java

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

輸出 ui

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);
複製代碼

本文同步發表於陌上寒我的博客spa

參考連接: Object.prototype.hasOwnProperty()prototype

hasOwnProperty 方法 (Object) (JavaScript)code

js屬性對象的hasOwnProperty方法cdn

相關文章
相關標籤/搜索