关于javascript:Do-not-access-Objectprototype-method-hasOwnProperty-问题原因及解决方法

31次阅读

共计 1355 个字符,预计需要花费 4 分钟才能阅读完成。

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

编码欢快❤️!


正文完
 0