本文介绍在JavaScript中使用hasOwnProperty时,因ESLint规则no-prototype-builtins导致的报错原因。通过Object.prototype.hasOwnProperty.call()方法调用,可避免从目标对象直接访问原型方法,从而解决该Lint错误并正确判断对象自身属性。
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属性JS中hasOwnProperty方法用法简介
hasOwnProperty用法
使用时可能会遇到的问题
由于ESLint规则升级,直接在对象上调用xxx.hasOwnProperty()可能触发no-prototype-builtins错误。
error Do not access Object.prototype method 'hasOwnProperty' from
target object no-prototype-builtins该错误提示禁止从目标对象直接访问Object原型方法。在ECMAScript 5.1中,Object.create支持指定[[Prototype]]创建对象。为避免直接调用原型方法,应使用call()方法。
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报错内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!