使用hasOwnProperty時報錯的解決方法
hasOwnProperty
hasOwnProperty這個方法是用來查找一個對象是否有某個屬性,且查找的屬性必須是對象本身的一個成員,但是不會去查找對象的原型鏈。
使用示例:
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對象沒有d屬性
使用時可能會遇到的問題
由于ESLint升級,在項(xiàng)目中直接使用xxx.hasOwnProperty()可能會導(dǎo)致:
error Do not access Object.prototype method 'hasOwnProperty' from target object no-prototype-builtins
這個錯誤提示大概就是說:不要從目標(biāo)對象上訪問 Object 原型方法。在ECMAScript 5.1中,新增了 Object.create,它支持使用指定的 [[Prototype]] 創(chuàng)建對象。我們可以通過使用call()方法來調(diào)用不屬于本身this對象的方法。
例如:
var a = { today: '2022年5月11號', weather: '陰天' show: function(){ return this.today+ '是' + this.weather } } var b = { today: '2022年5月30號', 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時報錯的解決方法的文章就介紹到這了,更多相關(guān)hasOwnProperty報錯內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JS遍歷Json字符串中鍵值對先轉(zhuǎn)成JSON對象再遍歷
這篇文章主要介紹了JS遍歷Json字符串中鍵值對的方法,先將Json字符串轉(zhuǎn)換成JSON對象,再進(jìn)行遍歷,需要的朋友可以參考下2014-08-08JavaScript高級函數(shù)應(yīng)用之分時函數(shù)實(shí)例分析
這篇文章主要介紹了JavaScript高級函數(shù)應(yīng)用之分時函數(shù),結(jié)合實(shí)例形式分析了javascript通過合理分時函數(shù)應(yīng)用避免瀏覽器卡頓或假死的相關(guān)操作技巧,需要的朋友可以參考下2018-08-08js數(shù)值計算時使用parseInt進(jìn)行數(shù)據(jù)類型轉(zhuǎn)換(jquery)
這篇文章主要介紹了js數(shù)值計算時使用parseInt進(jìn)行數(shù)據(jù)類型轉(zhuǎn)換(jquery),需要的朋友可以參考下2014-10-10