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

使用hasOwnProperty時(shí)報(bào)錯(cuò)的解決方法

 更新時(shí)間:2024年01月04日 15:10:32   作者:嘿!陳俊彥  
hasOwnProperty這個(gè)方法是用來查找一個(gè)對(duì)象是否有某個(gè)屬性,且查找的屬性必須是對(duì)象本身的一個(gè)成員,但是不會(huì)去查找對(duì)象的原型鏈,文中介紹了使用示例代碼及使用時(shí)可能會(huì)遇到的問題,對(duì)hasOwnProperty報(bào)錯(cuò)原因分析及解決方法感興趣的朋友一起看看吧

hasOwnProperty

hasOwnProperty這個(gè)方法是用來查找一個(gè)對(duì)象是否有某個(gè)屬性,且查找的屬性必須是對(duì)象本身的一個(gè)成員,但是不會(huì)去查找對(duì)象的原型鏈。
使用示例:

var obj = {
    a: 1,
    fun: function(){},
    c:{
        d: 5
    }
};
console.log(obj.hasOwnProperty('a'));  // true
console.log(obj.hasOwnProperty('fun'));  // true
console.log(obj.hasOwnProperty('c'));  // true
console.log(obj.c.hasOwnProperty('d'));  // true
console.log(obj.hasOwnProperty('d'));  // false, obj對(duì)象沒有d屬性

JS中hasOwnProperty方法用法簡介

hasOwnProperty用法

使用時(shí)可能會(huì)遇到的問題

由于ESLint升級(jí),在項(xiàng)目中直接使用xxx.hasOwnProperty()可能會(huì)導(dǎo)致:

error  Do not access Object.prototype method 'hasOwnProperty' from 
target object  no-prototype-builtins

這個(gè)錯(cuò)誤提示大概就是說:不要從目標(biāo)對(duì)象上訪問 Object 原型方法。在ECMAScript 5.1中,新增了 Object.create,它支持使用指定的 [[Prototype]] 創(chuàng)建對(duì)象。我們可以通過使用call()方法來調(diào)用不屬于本身this對(duì)象的方法。
例如:

var a = {
  today: '2022年5月11號(hào)',
  weather: '陰天'
  show: function(){
    return this.today+ '是' + this.weather
  }
}
var b = {
  today: '2022年5月30號(hào)',
  weather: '晴天'
}
//調(diào)用a的show方法,并用于b
b.show.call(a)  
console.log(b)  //輸出為:2022年5月30是晴天

所以解決該問題的方法為:將xxx.hasOwnProperty(‘yyy’)修改為Object.prototype.hasOwnProperty.call(xxx, ‘yyy’)。
代碼示例:

 handleEdit(todo) {
            // if(todo.hasOwnProperty('isEdit')){
            //    todo.isEdit = true;
            // }else{
            //   this.$set(todo,'isEdit',true)
            // }
            if(Object.prototype.hasOwnProperty.call(todo, 'isEdit')){
               todo.isEdit = true;
            }else{
              this.$set(todo,'isEdit',true)
            }
          },

到此這篇關(guān)于使用hasOwnProperty時(shí)報(bào)錯(cuò)的解決方法的文章就介紹到這了,更多相關(guān)hasOwnProperty報(bào)錯(cuò)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論