js中hasOwnProperty的屬性及例項用法詳解
阿新 • • 發佈:2021-11-03
1、不會保護hasOwnProperty被非法佔用,如果一個物件碰巧存在這個屬性, 就需要使用外部的hasOwnProperty 函式來獲取正確的結果。
2、當檢查物件上某個屬性是否存在時,hasOwnProperty www.cppcns.com是唯一可用的方法。
例項
var foo = { hasOwnProperty: function() { return false; },bar: 'Here be dragons' }; foo.hasOwnProperty('bar'); // 總是返回 false // 使用其它物件的 hasOwnProperty,並將其上下文設定為foo ({}).hasOwnProperty.call(foo,'bar'); // true
知識點擴充套件:
判斷自身屬性是否存在
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[HBEzqaVWname]); } else { alert(name); // toString or something else } }
注意 hasOwnProperty 作為屬性名
並沒有保護 hasOwnProperty 屬性名,因此,可能存在於一個包含此屬性名的物件,有必要使用一個可擴充套件的hasOwnProperty方法來獲取正確的結果:
var fhttp://www.cppcns.comoo = {
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
到此這篇關於js中hasOwnProperty的屬性及例項用法詳解的文章就介紹到這了,更多相關js中hasOwnProperty的屬性用法內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!