Object的hasOwnProperty()方法返回一個布爾值,判斷對象是否包含特定的自身(非繼承)屬性。
判斷自身屬性是否存在
var o = new Object();
o.prop = 'exists';
function changeO() {
o.newprop = o.prop;
delete o.prop;
}
o.hasOwnProperty('prop'); // true
changeO();
o.hasOwnProperty('prop'); // false
判斷自身屬性與繼承屬性
function foo() {
this.name = 'foo'
this.sayHi = function () {
console.log('Say Hi')
}
}
foo.prototype.sayGoodBy = function () {
console.log('Say Good By')
}
let myPro = new foo()
console.log(myPro.name) // foo
console.log(myPro.hasOwnProperty('name')) // true
console.log(myPro.hasOwnProperty('toString')) // false
console.log(myPro.hasOwnProperty('hasOwnProperty')) // fasle
console.log(myPro.hasOwnProperty('sayHi')) // true
console.log(myPro.hasOwnProperty('sayGoodBy')) // false
console.log('sayGoodBy' in myPro) // true
遍歷一個對象的所有自身屬性
在看開源項目的過程中,經常會看到類似如下的源碼。for...in循環對象的所有枚舉屬性,然后再使用hasOwnProperty()方法來忽略繼承屬性。
var buz = {
fog: 'stack'
};
for (var name in buz) {
if (buz.hasOwnProperty(name)) {
alert("this is fog (" + name + ") for sure. Value: " + buz[name]);
}
else {
alert(name); // toString or something else
}
}
注意 hasOwnProperty 作為屬性名
JavaScript 並沒有保護 hasOwnProperty 屬性名,因此,可能存在於一個包含此屬性名的對象,有必要使用一個可擴展的hasOwnProperty方法來獲取正確的結果:
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
foo.hasOwnProperty('bar'); // 始終返回 false
// 如果擔心這種情況,可以直接使用原型鏈上真正的 hasOwnProperty 方法
// 使用另一個對象的`hasOwnProperty` 並且call
({}).hasOwnProperty.call(foo, 'bar'); // true
// 也可以使用 Object 原型上的 hasOwnProperty 屬性
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
參考鏈接
[完]
