欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

js屬性對(duì)象的hasOwnProperty方法的使用

 更新時(shí)間:2021年02月05日 10:29:17   作者:weiqinl  
這篇文章主要介紹了js屬性對(duì)象的hasOwnProperty方法的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

Object的hasOwnProperty()方法返回一個(gè)布爾值,判斷對(duì)象是否包含特定的自身(非繼承)屬性。

判斷自身屬性是否存在

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

遍歷一個(gè)對(duì)象的所有自身屬性

在看開源項(xiàng)目的過程中,經(jīng)常會(huì)看到類似如下的源碼。for...in循環(huán)對(duì)象的所有枚舉屬性,然后再使用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 屬性名,因此,可能存在于一個(gè)包含此屬性名的對(duì)象,有必要使用一個(gè)可擴(kuò)展的hasOwnProperty方法來獲取正確的結(jié)果:

var foo = {
  hasOwnProperty: function() {
    return false;
  },
  bar: 'Here be dragons'
};

foo.hasOwnProperty('bar'); // 始終返回 false

// 如果擔(dān)心這種情況,可以直接使用原型鏈上真正的 hasOwnProperty 方法
// 使用另一個(gè)對(duì)象的`hasOwnProperty` 并且call
({}).hasOwnProperty.call(foo, 'bar'); // true

// 也可以使用 Object 原型上的 hasOwnProperty 屬性
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true

參考鏈接

到此這篇關(guān)于js屬性對(duì)象的hasOwnProperty方法的使用的文章就介紹到這了,更多相關(guān)js hasOwnProperty內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論