Do not access Object.prototype method 'hasOwnProperty' 问题原因及解决方法

简介: 使用Vue.js启动新项目将自动生成配置为与ESLint一起使用的样板。ESLint是可插拔和可配置的Linter工具,可帮助您识别和报告JavaScript中的不良模式,因此您可以轻松维护代码质量。如果您在不受控制的情况下开始编程,则可能会引入一些对ESLint不利的做法。

如何修复ESLint错误:请勿从目标对象无原型内置对象访问Object.prototype方法'hasOwnProperty'


使用Vue.js启动新项目将自动生成配置为与ESLint一起使用的样板。ESLint是可插拔和可配置的Linter工具,可帮助您识别和报告JavaScript中的不良模式,因此您可以轻松维护代码质量。如果您在不受控制的情况下开始编程,则可能会引入一些对ESLint不利的做法。例如,最简单的事情之一,例如检查某个对象是否具有特定的属性:

let events = {"some-index": false};
let key = "some-index";
if(events.hasOwnProperty(key)){
    // Do Something ...
    console.log("The object has the property");
}

由于该no-prototype-builtins规则,这将在您尝试构建应用程序时触发提到的异常。在ECMAScript 5.1中,Object.create添加了该方法,该方法可以创建具有指定[[Prototype]]的对象。Object.create(null)是用于创建将用作Map的对象的常见模式。当假设对象将具有from的属性时,这可能会导致错误Object.prototype。该规则no-prototype-builtins防止Object.prototype直接从对象调用方法。有关no-prototype- builtins的更多信息,请在此处访问ESLint的官方文档

在本文中,我将与您分享不同的方法,以避免在尝试构建应用程序时出现此错误。


解决方案

有多种方法可以避免此错误,第一种方法是简单地从Object的原型访问hasOwnPropertyMethod并使用call执行函数:

let events = {"some-index": false};
let key = "some-index";
if(Object.prototype.hasOwnProperty.call(events, key)) {
    // This would compile without any issue !
    console.log("The object has the property");
}

只要您没有做任何使属性不可枚举的检查对象的等效方法:

let events = {"some-index": false};
let key = "some-index";
if({}.propertyIsEnumerable.call(events, key)) {
    // This would compile without any issue !
    console.log("The object has the property");
}

或通过getOwnPropertyDescriptor方法:

let events = {"some-index": false};
let key = "some-index";
if(!!Object.getOwnPropertyDescriptor(events, key)) {
    // This would compile without any issue !
    console.log("The object has the property");
}

编码愉快❤️!

相关文章
|
存储 对象存储
【阿里云OSS】You have no right to access this object because of bucket acl.
【阿里云OSS】You have no right to access this object because of bucket acl.
7093 1
【阿里云OSS】You have no right to access this object because of bucket acl.
|
数据可视化 Python
AttributeError: ‘Rectangle‘ object has no property ‘normed‘ 解决方法 matplotlib绘图
AttributeError: ‘Rectangle‘ object has no property ‘normed‘
903 0
AttributeError: ‘Rectangle‘ object has no property ‘normed‘ 解决方法 matplotlib绘图
|
Python
ValueError: Object arrays cannot be loaded when allow_pickle=False 解决方法
ValueError: Object arrays cannot be loaded when allow_pickle=False
423 0
ValueError: Object arrays cannot be loaded when allow_pickle=False 解决方法
|
存储 SQL Oracle
JDBC第二天~JDBC之 DAO(Data Access Object)
JDBC第二天~JDBC之 DAO(Data Access Object)
135 0
JDBC第二天~JDBC之 DAO(Data Access Object)
|
对象存储
访问oss出现报错:You have no right to access this object because of bucket acl
访问oss出现报错:You have no right to access this object because of bucket acl 也配置bucket权限和RAM用户权限了但是还是报错,然后看了下代码,发现到httpClient.execute(req)就直接403了 能问下大佬们这是什么问题吗,百度也没找到
|
SQL
SAP Hybris和ABAP Netweaver里的DAO(Data access object)
SAP Hybris和ABAP Netweaver里的DAO(Data access object)
120 0
SAP Hybris和ABAP Netweaver里的DAO(Data access object)
下一篇
无影云桌面