使用hasOwnProperty時(shí)報(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屬性
使用時(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)文章
JS遍歷Json字符串中鍵值對(duì)先轉(zhuǎn)成JSON對(duì)象再遍歷
這篇文章主要介紹了JS遍歷Json字符串中鍵值對(duì)的方法,先將Json字符串轉(zhuǎn)換成JSON對(duì)象,再進(jìn)行遍歷,需要的朋友可以參考下2014-08-08JavaScript高級(jí)函數(shù)應(yīng)用之分時(shí)函數(shù)實(shí)例分析
這篇文章主要介紹了JavaScript高級(jí)函數(shù)應(yīng)用之分時(shí)函數(shù),結(jié)合實(shí)例形式分析了javascript通過合理分時(shí)函數(shù)應(yīng)用避免瀏覽器卡頓或假死的相關(guān)操作技巧,需要的朋友可以參考下2018-08-08js數(shù)值計(jì)算時(shí)使用parseInt進(jìn)行數(shù)據(jù)類型轉(zhuǎn)換(jquery)
這篇文章主要介紹了js數(shù)值計(jì)算時(shí)使用parseInt進(jìn)行數(shù)據(jù)類型轉(zhuǎn)換(jquery),需要的朋友可以參考下2014-10-10