Error do not access object prototype method hasownproperty from target object no prototype builtins

A pluggable and configurable linter tool for identifying and reporting on patterns in JavaScript. Maintain your code quality with ease.

Disallow calling some Object.prototype methods directly on objects

Recommended

The "extends": "eslint:recommended" property in a configuration file enables this rule

In ECMAScript 5.1, Object.create was added, which enables the creation of objects with a specified [[Prototype]]. Object.create(null) is a common pattern used to create objects that will be used as a Map. This can lead to errors when it is assumed that objects will have properties from Object.prototype. This rule prevents calling some Object.prototype methods directly from an object.

Additionally, objects can have properties that shadow the builtins on Object.prototype, potentially causing unintended behavior or denial-of-service security vulnerabilities. For example, it would be unsafe for a webserver to parse JSON input from a client and call hasOwnProperty directly on the resulting object, because a malicious client could send a JSON value like {"hasOwnProperty": 1} and cause the server to crash.

To avoid subtle bugs like this, it’s better to always call these methods from Object.prototype. For example, foo.hasOwnProperty("bar") should be replaced with Object.prototype.hasOwnProperty.call(foo, "bar").

Rule Details

This rule disallows calling some Object.prototype methods directly on object instances.

Examples of incorrect code for this rule:

/*eslint no-prototype-builtins: "error"*/

var hasBarProperty = foo.hasOwnProperty("bar");

var isPrototypeOfBar = foo.isPrototypeOf(bar);

var barIsEnumerable = foo.propertyIsEnumerable("bar");

Examples of correct code for this rule:

/*eslint no-prototype-builtins: "error"*/

var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");

var isPrototypeOfBar = Object.prototype.isPrototypeOf.call(foo, bar);

var barIsEnumerable = {}.propertyIsEnumerable.call(foo, "bar");

When Not To Use It

You may want to turn this rule off if your code only touches objects with hardcoded keys, and you will never use an object that shadows an Object.prototype method or which does not inherit from Object.prototype.

Version

This rule was introduced in ESLint v2.11.0.

Resources

  • Rule source
  • Tests source

Learn how to prevent the «do-not-access-objectprototype-method» error from appearing when building your JavaScript application.

Starting a new project with Vue.js will automatically generate a boilerplate that is configured to work with ESLint.  ESLint is a pluggable and configurable linter tool that helps you to identify and report bad patterns in JavaScript, so you can maintain your code quality with ease. If you start programming without control, you may probably introduce some practices that aren’t good for ESLint. For example, one of the most simple things like checking that some object has a specific property:

let events = {"some-index": false};
let key = "some-index";

if(events.hasOwnProperty(key)){
    // Do Something ...
    console.log("The object has the property");
}

This would trigger the mentioned exception when you try to build your application, because of the no-prototype-builtins rule. In ECMAScript 5.1, the Object.create method was added, which enables the creation of objects with a specified [[Prototype]]. Object.create(null) is a common pattern used to create objects that will be used as a Map. This can lead to errors when it is assumed that objects will have properties from Object.prototype. The rule no-prototype-builtins prevents calling Object.prototype methods directly from an object. For more information about the no-prototype-builtins, please visit the official documentation of ESLint here.

In this article, I will share with you different ways to avoid this error from appearing when trying to build your application.

Solutions

There are multiple ways to circumvent this error, the first one is to simply access the hasOwnPropertyMethod from the prototype of Object and execute the function using 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");
}

An equivalent way to check if the object has the property, as long as you haven’t done anything to make the properties not enumerable:

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");
}

Or through the getOwnPropertyDescriptor method:

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");
}

Happy coding ❤️!

Алексей

Подскажите, допустимо ли использовать такой код?
Ревью

Линтер ругается:

Do not access Object.prototype method 'hasOwnProperty' from target object no-prototype-builtins

но функция работает.


4


0

Svetlana

Алексей, Об этом подробно рассказано тут : Проверка существования свойства


0

Алексей

Svetlana, мне кажется что мое решение соответствует правильному примеру из урока. Что именно с ним не так?


0

Радислав Ялилов

В уроке есть такие строки

Именно поэтому прямой вызов метода hasOwnProperty на проверяемом объекте считается плохой практикой и линтер будет ругаться.

А вот примеры из документации
// bad
console.log(object.hasOwnProperty(key));

// good
console.log(Object.prototype.hasOwnProperty.call(object, key));

// best
const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module                 
scope.
console.log(has.call(object, key));

Или лучше использовать метод из лодаша


0

Бауыржан Есетов

Радислав Ялилов, но как спасает вариант, который предлагает линтер

Object.prototype.hasOwnProperty.call(object, key)

от вероятной ошибки озвученной в уроке?


0

Labrador retriever puppy walking on green grass

Sometimes, we want to fix Object.hasOwnProperty() yielding the ESLint ‘no-prototype-builtins’ error with JavaScript.

In this article, we’ll look at how to fix Object.hasOwnProperty() yielding the ESLint ‘no-prototype-builtins’ error with JavaScript.

How to fix Object.hasOwnProperty() yielding the ESLint ‘no-prototype-builtins’ error with JavaScript?

To fix Object.hasOwnProperty() yielding the ESLint ‘no-prototype-builtins’ error with JavaScript, we can use Object.prototype.hasOwnProperty.call instead of the hasOwnProperty of an object.

For instance, we write

Object.prototype.hasOwnProperty.call(obj, prop);

to call hasOwnProperty on obj with obj as the value of this.

We pass in prop as the 2nd argument to check if prop exists in obj.

Conclusion

To fix Object.hasOwnProperty() yielding the ESLint ‘no-prototype-builtins’ error with JavaScript, we can use Object.prototype.hasOwnProperty.call instead of the hasOwnProperty of an object.

Web developer specializing in React, Vue, and front end development.

View Archive

Запретить вызов некоторых методов Object.prototype непосредственно для объектов

✅ Recommended

Свойство "extends": "eslint:recommended" в файле конфигурации включает это правило .

В ECMAScript 5.1 был добавлен Object.create , который позволяет создавать объекты с указанным [[Prototype]] . Object.create(null) — это общий шаблон, используемый для создания объектов, которые будут использоваться в качестве карты. Это может привести к ошибкам, если предполагается, что объекты будут иметь свойства из Object.prototype . Это правило предотвращает вызов некоторых методов Object.prototype непосредственно из объекта.

Кроме того, объекты могут иметь свойства, которые скрывают встроенные в Object.prototype свойства, что может привести к непреднамеренному поведению или уязвимостям защиты от отказа в обслуживании. Например, для веб-сервера было бы небезопасно анализировать ввод JSON от клиента и вызывать hasOwnProperty непосредственно для полученного объекта, поскольку злонамеренный клиент может отправить значение JSON, например {"hasOwnProperty": 1} и вызвать сбой сервера.

Чтобы избежать таких тонких ошибок, лучше всегда вызывать эти методы из Object.prototype . Например, foo.hasOwnProperty("bar") следует заменить на Object.prototype.hasOwnProperty.call(foo, "bar") .

Rule Details

Это правило запрещает вызывать некоторые методы Object.prototype непосредственно для экземпляров объекта.

Примеры неправильного кода для этого правила:

var hasBarProperty = foo.hasOwnProperty("bar");var isPrototypeOfBar = foo.isPrototypeOf(bar);var barIsEnumerable = foo.propertyIsEnumerable("bar");

Примеры правильного кода для этого правила:

var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");var isPrototypeOfBar = Object.prototype.isPrototypeOf.call(foo, bar);var barIsEnumerable = {}.propertyIsEnumerable.call(foo, "bar");

Когда не использовать его

Вы можете отключить это правило, если ваш код касается только объектов с жестко запрограммированными ключами, и вы никогда не будете использовать объект, который Object.prototype метод Object.prototype или который не наследуется от Object.prototype .

Version

Это правило было введено в ESLint v2.11.0.

Resources

  • Rule source
  • Tests source


ESLint

8.30

  • no-promise-executor-return

    Запретить возврат значений из функций исполнителей Promise Новый конструктор Promise принимает один аргумент,называемый исполнителем.

  • no-proto

    Запретить использование свойства __proto__Свойство __proto__было устаревшим в ECMAScript 3.1 и не должно использоваться в коде.

  • no-redeclare

    Запретить повторное объявление переменной Свойство «extends»: «eslint:recommended» файл конфигурации включает это правило. В JavaScript возможно повторное объявление

  • no-regex-spaces

    Запретить использование нескольких пробелов в регулярных выражениях Свойство «extends»: «eslint:recommended» файл конфигурации включает это правило. Сообщалось о некоторых проблемах.

I am using the following logic to get the i18n string of the given key.

export function i18n(key) {
  if (entries.hasOwnProperty(key)) {
    return entries[key];
  } else if (typeof (Canadarm) !== 'undefined') {
    try {
      throw Error();
    } catch (e) {
      Canadarm.error(entries['dataBuildI18nString'] + key, e);
    }
  }
  return entries[key];
}

I am using ESLint in my project. I am getting the following error:

Do not access Object.prototype method ‘hasOwnProperty’ from target object.
It is a ‘no-prototype-builtins‘ error.

How do I change my code to resolve this error ? I don’t want to disable this rule.

4 Answers

You can access it via Object.prototype:

Object.prototype.hasOwnProperty.call(obj, prop);

That should be safer, because

  • Not all objects inherit from Object.prototype
  • Even for objects which inherit from Object.prototype, the hasOwnProperty method could be shadowed by something else.

Of course, the code above assumes that

  • The global Object has not been shadowed or redefined
  • The native Object.prototype.hasOwnProperty has not been redefined
  • No call own property has been added to Object.prototype.hasOwnProperty
  • The native Function.prototype.call has not been redefined

If any of these does not hold, attempting to code in a safer way, you could have broken your code!

Another approach which does not need call would be

!!Object.getOwnPropertyDescriptor(obj, prop);

For your specific case, the following examples shall work:

if(Object.prototype.hasOwnProperty.call(entries, "key")) {
    //rest of the code
}

OR

if(Object.prototype.isPrototypeOf.call(entries, key)) {
    //rest of the code
}

OR

if({}.propertyIsEnumerable.call(entries, "key")) {
    //rest of the code
}

It seems like this would also work:

key in entries

since that will return a boolean on whether or not the key exists inside the object?

I hope I won’t get downvoted for this, probably will, but !

var a = {b: "I'm here"}
if (a["b"]) { console.log(a["b"]) }
if (a["c"]) { console.log("Never going to happen") }

Has, insofar, never broken my code 😬 But I’m not sure if it is the case in all web browsers…

(Also, if Canadarm is undefined, your code seem to return entries[key]; even if key is not in entries…)

Disallow use of Object.prototypes builtins directly (no-prototype-builtins)

In ECMAScript 5.1, Object.create was added, which enables the creation of objects with a specified [[Prototype]]. Object.create(null) is a common pattern used to create objects that will be used as a Map. This can lead to errors when it is assumed that objects will have properties from Object.prototype. This rule prevents calling Object.prototype methods directly from an object.

Rule Details

This rule disallows calling some Object.prototype methods directly on object instances.

Examples of incorrect code for this rule:

/*eslint no-prototype-builtins: "error"*/

var hasBarProperty = foo.hasOwnProperty("bar");

var isPrototypeOfBar = foo.isPrototypeOf(bar);

var barIsEnumerable = foo.propertyIsEnumerable("bar");

Examples of correct code for this rule:

/*eslint no-prototype-builtins: "error"*/

var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");

var isPrototypeOfBar = Object.prototype.isPrototypeOf.call(foo, bar);

var barIsEnumerable = {}.propertyIsEnumerable.call(foo, "bar");

When Not To Use It

You may want to turn this rule off if you will never use an object that shadows an Object.prototype method or which does not inherit from Object.prototype.

Version

This rule was introduced in ESLint 2.11.0.

Resources

  • Rule source
  • Documentation source

Понравилась статья? Поделить с друзьями:
  • Error dmg image is corrupted
  • Error dlopen failed
  • Error dll prototype2engine dll does not contain required exports что делать
  • Error dll msvcr120 dll
  • Error dll msvcp100 dll