使用hasOwnProperty时报错的解决方法
作者:嘿!陈俊彦
hasOwnProperty这个方法是用来查找一个对象是否有某个属性,且查找的属性必须是对象本身的一个成员,但是不会去查找对象的原型链,文中介绍了使用示例代码及使用时可能会遇到的问题,对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升级,在项目中直接使用xxx.hasOwnProperty()可能会导致:
error Do not access Object.prototype method 'hasOwnProperty' from target object no-prototype-builtins
这个错误提示大概就是说:不要从目标对象上访问 Object 原型方法。在ECMAScript 5.1中,新增了 Object.create,它支持使用指定的 [[Prototype]] 创建对象。我们可以通过使用call()方法来调用不属于本身this对象的方法。
例如:
var a = {
today: '2022年5月11号',
weather: '阴天'
show: function(){
return this.today+ '是' + this.weather
}
}
var b = {
today: '2022年5月30号',
weather: '晴天'
}
//调用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)
}
},到此这篇关于使用hasOwnProperty时报错的解决方法的文章就介绍到这了,更多相关hasOwnProperty报错内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
