使用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报错内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
layui 图片上传+表单提交+ Spring MVC的实例
今天小编就为大家分享一篇layui 图片上传+表单提交+ Spring MVC的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2019-09-09
JavaScript用Number方法实现string转int
parseInt方法在format'00'开头的数字时会当作2进制转10进制,所以建议string转int最好用Number方法2014-05-05


最新评论