js中hasOwnProperty的屬性及實(shí)例用法詳解
1、js不會保護(hù)hasOwnProperty被非法占用,如果一個對象碰巧存在這個屬性, 就需要使用外部的hasOwnProperty 函數(shù)來獲取正確的結(jié)果。
2、當(dāng)檢查對象上某個屬性是否存在時,hasOwnProperty 是唯一可用的方法。
實(shí)例
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
foo.hasOwnProperty('bar'); // 總是返回 false
// 使用其它對象的 hasOwnProperty,并將其上下文設(shè)置為foo
({}).hasOwnProperty.call(foo, 'bar'); // true
知識點(diǎn)擴(kuò)展:
判斷自身屬性是否存在
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
遍歷一個對象的所有自身屬性
在看開源項(xiàng)目的過程中,經(jīng)常會看到類似如下的源碼。for...in循環(huán)對象的所有枚舉屬性,然后再使用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 并沒有保護(hù) hasOwnProperty 屬性名,因此,可能存在于一個包含此屬性名的對象,有必要使用一個可擴(kuò)展的hasOwnProperty方法來獲取正確的結(jié)果:
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
foo.hasOwnProperty('bar'); // 始終返回 false
// 如果擔(dān)心這種情況,可以直接使用原型鏈上真正的 hasOwnProperty 方法
// 使用另一個對象的`hasOwnProperty` 并且call
({}).hasOwnProperty.call(foo, 'bar'); // true
// 也可以使用 Object 原型上的 hasOwnProperty 屬性
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
到此這篇關(guān)于js中hasOwnProperty的屬性及實(shí)例用法詳解的文章就介紹到這了,更多相關(guān)js中hasOwnProperty的屬性用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
微信小程序網(wǎng)絡(luò)數(shù)據(jù)請求服務(wù)實(shí)現(xiàn)詳解
ES2020讓代碼更優(yōu)美的運(yùn)算符 (?.) (??)
JavaScript使表單中的內(nèi)容顯示在屏幕上的方法
新人報道,發(fā)個小技巧(js數(shù)組重復(fù)判斷)
jQuery EasyUI window窗口使用實(shí)例代碼

