29 lines
1.5 KiB
Plaintext
29 lines
1.5 KiB
Plaintext
== Why is this an issue?
|
|
|
|
The `Object.hasOwn()` method was introduced in ES2022 as a replacement for the more verbose `Object.prototype.hasOwnProperty.call()`. These methods return `true` if the specified property of an object exists as its _own_ property. If the property is only available further down the prototype chain or does not exist at all - the methods return `false`.
|
|
|
|
If you are still using the old method - replace it with a simpler and more concise alternative.
|
|
|
|
You should also avoid calling the `obj.hasOwnProperty()` method directly, without using `Object.prototype` as a source. This can lead to a runtime error if `obj.prototype` is `null` and therefore `obj.hasOwnProperty` is undefined. The static method `Object.hasOwn()` does not depend on the `obj.prototype` and is therefore safe to use in such cases.
|
|
|
|
[source,javascript]
|
|
----
|
|
Object.prototype.hasOwnProperty.call(obj, "propertyName"); // Noncompliant
|
|
Object.hasOwnProperty.call(obj, "propertyName"); // Noncompliant
|
|
({}).hasOwnProperty.call(obj, "propertyName"); // Noncompliant
|
|
|
|
----
|
|
|
|
To fix the code replace `hasOwnProperty()` with `Object.hasOwn()`
|
|
|
|
[source,javascript]
|
|
----
|
|
Object.hasOwn(obj, "propertyName");
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn[Object.hasOwn()]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty[Object.prototype.hasOwnProperty()]
|