如何修复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");}

编码欢快❤️!