最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

js屬性對象的hasOwnProperty方法的使用

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

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

遍歷一個對象的所有自身屬性

在看開源項(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方法的使用的文章就介紹到這了,更多相關(guān)js hasOwnProperty內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

错那县| 台东市| 楚雄市| 洪湖市| 来凤县| 吉林市| 托里县| 韶关市| 会宁县| 昌都县| 惠安县| 金昌市| 汝城县| 万荣县| 揭阳市| 北碚区| 绵阳市| 尼玛县| 祥云县| 玉屏| 六枝特区| 常德市| 娄烦县| 平阴县| 安宁市| 宜章县| 武平县| 霍林郭勒市| 二手房| 察雅县| 渑池县| 佛冈县| 德阳市| 和田市| 永州市| 富宁县| 阳曲县| 奈曼旗| 山西省| 满洲里市| 丹凤县|