如何修复ESLint错误:Do not access Object.prototype method ‘hasOwnProperty’ from target object no-prototype-builtins

2021年11月29日23:41:20 发表评论 1,685 次浏览

如何修复错误Do not access Object.prototype method?了解如何在构建 JavaScript 应用程序时防止出现这个错误。

如何修复ESLint错误:Do not access Object.prototype method 'hasOwnProperty' from target object no-prototype-builtins
Do not access Object.prototype method解决办法

使用 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 的对象。当假定对象将具有来自Object.prototype的属性时,这可能会导致错误。该规则no-prototype-builtins防止Object.prototype直接从对象调用方法。有关 no-prototype- builtins 的更多信息,请在此处访问 ESLint 的官方文档

在本文中,我将与你分享在尝试构建应用程序时避免出现此错误的不同方法,包括对错误Do not access Object.prototype method解决办法。

解决方案

如何修复错误Do not access Object.prototype method?有多种方法可以绕过这个错误,第一种是简单地从 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");
}

快乐编码❤️!

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: