Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replaced hasOwnProperty with hasOwn in code examples #18190

Merged
merged 9 commits into from
Jul 13, 2022
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ Let's have a brief look at how we'd access the API using Node.js and [node-sauce
myAccount.getJobs(function (err, jobs) {
// Get a list of all your jobs
for (let k in jobs) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we couldn't use for...of here and get one step further in simplifying this to:

          for (const job of jobs) {
            myAccount.showJob(job.id, function (err, res) {
              let str = res.id + ": Status: " + res.status;
              if (res.error) {
                str += "\033[31m Error: " + res.error + " \033[0m";
              }
              console.log(str);
            }
          }

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, make sense. Thanks. I implemented the change.

if ( jobs.hasOwnProperty( k )) {
if (Object.hasOwn(jobs, k)) {
myAccount.showJob(jobs[k].id, function (err, res) {
let str = res.id + ": Status: " + res.status;
if (res.error) {
Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/api/htmlelement/style/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ var elementStyle = element.style;
var computedStyle = window.getComputedStyle(element, null);

for (prop in elementStyle) {
if (elementStyle.hasOwnProperty(prop)) {
if (Object.hasOwn(elementStyle, prop)) {
out += " " + prop + " = '" + elementStyle[prop] + "' > '" + computedStyle[prop] + "'\n";
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,7 @@ The last significant piece of the puzzle: code that displays, for the user's ref
```js
let supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
for (let constraint in supportedConstraints) {
if (supportedConstraints.hasOwnProperty(constraint)) {
if (Object.hasOwn(supportedConstraints, constraint)) {
let elem = document.createElement("li");

elem.innerHTML = "<code><a href='https://developer.mozilla.org/docs/Web/API/MediaTrackSupportedConstraints/"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ let constraintList = document.getElementById("constraintList");
let supportedConstraints = navigator.mediaDevices.getSupportedConstraints();

for (let constraint in supportedConstraints) {
if (supportedConstraints.hasOwnProperty(constraint)) {
if (Object.hasOwn(supportedConstraints, constraint)) {
let elem = document.createElement("li");

elem.innerHTML = "<code>" + constraint + "</code>";
Expand Down
14 changes: 7 additions & 7 deletions files/en-us/web/api/web_workers_api/using_web_workers/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -369,8 +369,8 @@ We finish QueryableWorker with the `onmessage` method. If the worker has the cor
```js
worker.onmessage = function(event) {
if (event.data instanceof Object &&
event.data.hasOwnProperty('queryMethodListener') &&
event.data.hasOwnProperty('queryMethodArguments')) {
Object.hasOwn(event.data, 'queryMethodListener') &&
Object.hasOwn(event.data, 'queryMethodArguments')) {
listeners[event.data.queryMethodListener].apply(instance, event.data.queryMethodArguments);
} else {
this.defaultListener.call(instance, event.data);
Expand Down Expand Up @@ -414,8 +414,8 @@ And the `onmessage` method is now trivial:
```js
onmessage = function(event) {
if (event.data instanceof Object &&
event.data.hasOwnProperty('queryMethod') &&
event.data.hasOwnProperty('queryMethodArguments')) {
Object.hasOwn(event.data, 'queryMethod') &&
Object.hasOwn(event.data, 'queryMethodArguments')) {
queryableFunctions[event.data.queryMethod]
.apply(self, event.data.queryMethodArguments);
} else {
Expand Down Expand Up @@ -487,8 +487,8 @@ Here are the full implementation:

worker.onmessage = function(event) {
if (event.data instanceof Object &&
event.data.hasOwnProperty('queryMethodListener') &&
event.data.hasOwnProperty('queryMethodArguments')) {
Object.hasOwn(event.data, 'queryMethodListener') &&
Object.hasOwn(event.data, 'queryMethodArguments')) {
listeners[event.data.queryMethodListener].apply(instance, event.data.queryMethodArguments);
} else {
this.defaultListener.call(instance, event.data);
Expand Down Expand Up @@ -546,7 +546,7 @@ function reply() {
}

onmessage = function(oEvent) {
if (oEvent.data instanceof Object && oEvent.data.hasOwnProperty('queryMethod') && oEvent.data.hasOwnProperty('queryMethodArguments')) {
if (oEvent.data instanceof Object && Object.hasOwn(oEvent.data, 'queryMethod') && Object.hasOwn(oEvent.data, 'queryMethodArguments')) {
queryableFunctions[oEvent.data.queryMethod].apply(self, oEvent.data.queryMethodArguments);
} else {
defaultReply(oEvent.data);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ Note that this is not the most efficient algorithm for all cases, but useful for
const SimplePropertyRetriever = {
getOwnEnumerables(obj) {
return this._getPropertyNames(obj, true, false, this._enumerable);
// Or could use for..in filtered with hasOwnProperty or just this: return Object.keys(obj);
// Or could use for..in filtered with Object.hasOwn or just this: return Object.keys(obj);
},
getOwnNonenumerables(obj) {
return this._getPropertyNames(obj, true, false, this._notEnumerable);
Expand Down Expand Up @@ -128,4 +128,5 @@ const SimplePropertyRetriever = {
- [`Object.getOwnPropertySymbols()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols)
- [`Object.keys()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)
- [`Object.getOwnPropertyDescriptors()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptors)
- [`Object.hasOwn()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn)
- [`Reflect.ownKeys()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/ownKeys)
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ emp[2] = 'August West'
> let arr = []
> arr[3.4] = 'Oranges'
> console.log(arr.length) // 0
> console.log(arr.hasOwnProperty(3.4)) // true
> console.log(Object.hasOwn(arr, 3.4)) // true
> ```

You can also populate an array when you create it:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,8 @@ You can use the bracket notation with [`for...in`](/en-US/docs/Web/JavaScript/Re
function showProps(obj, objName) {
let result = '';
for (const i in obj) {
// obj.hasOwnProperty() is used to exclude properties from the object's prototype chain
if (obj.hasOwnProperty(i)) {
// obj.hasOwn is used to exclude properties from the object's prototype chain and only show "own properties"
if (Object.hasOwn(obj, i)) {
result += `${objName}.${i} = ${obj[i]}\n`;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class ClassWithStaticField {
static staticField
}

console.assert(ClassWithStaticField.hasOwnProperty('staticField'))
console.assert(Object.hasOwn(ClassWithStaticField, 'staticField'))
console.log(ClassWithStaticField.staticField)
// expected output: "undefined"
```
Expand Down Expand Up @@ -135,7 +135,7 @@ class ClassWithInstanceField {
}

const instance = new ClassWithInstanceField()
console.assert(instance.hasOwnProperty('instanceField'))
console.assert(Object.hasOwn(instance, 'instanceField'))
console.log(instance.instanceField)
// expected output: "undefined"
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ foo.bar; // ReferenceError: reference to undefined property "bar"
To avoid the error, you need to either add a definition for `bar` to the
object or check for the existence of the `bar` property before trying to
access it; ways to do that include using the {{jsxref("Operators/in", "in")}} operator,
or the {{jsxref("Object.prototype.hasOwnProperty()")}} method, like this:
or the {{jsxref("Object.hasOwn()")}} method, like this:

```js example-good
const foo = {};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ browser-compat: javascript.builtins.Object.assign

The **`Object.assign()`** method
copies all {{jsxref("Object/propertyIsEnumerable", "enumerable", "", 1)}}
{{jsxref("Object/hasOwnProperty", "own properties", "", 1)}} from one or more
{{jsxref("Object/hasOwn", "own properties", "", 1)}} from one or more
_source objects_ to a _target object_. It returns the modified target
object.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ console.log(Object.getOwnPropertyNames(my_obj).sort());
// logs ["foo", "getFoo"]
```

If you want only the enumerable properties, see {{jsxref("Object.keys()")}} or use a {{jsxref("Statements/for...in", "for...in")}} loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter is filtered with {{jsxref("Object.prototype.hasOwnProperty()", "hasOwnProperty()")}}).
If you want only the enumerable properties, see {{jsxref("Object.keys()")}} or use a {{jsxref("Statements/for...in", "for...in")}} loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter is filtered with {{jsxref("Object.hasOwn()", "hasOwn()")}}).

Items on the prototype chain are not listed:

Expand Down Expand Up @@ -141,7 +141,7 @@ console.log(nonenum_only);

- [Polyfill of `Object.getOwnPropertyNames` in `core-js`](https://github.com/zloirock/core-js#ecmascript-object)
- [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
- {{jsxref("Object.prototype.hasOwnProperty()")}}
- {{jsxref("Object.hasOwn()")}}
- {{jsxref("Object.prototype.propertyIsEnumerable()")}}
- {{jsxref("Object.create()")}}
- {{jsxref("Object.keys()")}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ const current = Object.prototype.valueOf;
// Since my property "-prop-value" is cross-cutting and isn't always
// on the same prototype chain, I want to modify Object.prototype:
Object.prototype.valueOf = function() {
if (this.hasOwnProperty('-prop-value')) {
if (Object.hasOwn(this, '-prop-value')) {
return this['-prop-value'];
} else {
// It doesn't look like one of my objects, so let's fall back on
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ delete object['property']
### Return value

`true` for all cases except when the property is an
{{jsxref("Object.hasOwnProperty", "own")}} {{jsxref("Errors/Cant_delete", "non-configurable")}} property, in which case, `false` is returned in
{{jsxref("Object.hasOwn")}} {{jsxref("Errors/Cant_delete", "non-configurable")}} property, in which case, `false` is returned in
non-strict mode.

### Exceptions
Expand Down
4 changes: 2 additions & 2 deletions files/en-us/web/javascript/reference/operators/in/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ let empties = new Array(3).fill(undefined)

The `in` operator returns `true` for properties in the prototype
chain. (If you want to check for only _non-inherited_ properties,
use {{jsxref("Object.prototype.hasOwnProperty()")}} instead.)
use {{jsxref("Object.hasOwn()")}} instead.)

```js
'toString' in {} // returns true
Expand Down Expand Up @@ -161,6 +161,6 @@ The code fragment below demonstrates a static function that checks whether a spe

- [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in)
- [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/delete)
- {{jsxref("Object.prototype.hasOwnProperty()")}}
- {{jsxref("Object.hasOwn()")}}
- {{jsxref("Reflect.has()")}}
- [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ assert(Object.getPrototypeOf(obj3) === protoObj)

let obj4 = {__proto__: 'not an object or null'}
assert(Object.getPrototypeOf(obj4) === Object.prototype)
assert(!obj4.hasOwnProperty('__proto__'))
assert(!Object.hasOwn(obj4, '__proto__'))
```

Only a single prototype setter is permitted in an object literal. Multiple prototype setters are a syntax error.
Expand All @@ -288,7 +288,7 @@ let __proto__ = 'variable'

let obj1 = {__proto__}
assert(Object.getPrototypeOf(obj1) === Object.prototype)
assert(obj1.hasOwnProperty('__proto__'))
assert(Object.hasOwn(obj1, '__proto__'))
assert(obj1.__proto__ === 'variable')

let obj2 = {__proto__() { return 'hello'; }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,5 +160,5 @@ investigating whether to remove the nonstandard behavior as well.
- [Iterators and Generator functions](/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) (usable with `for...of` syntax)
- [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
- {{jsxref("Object.getOwnPropertyNames()")}}
- {{jsxref("Object.prototype.hasOwnProperty()")}}
- {{jsxref("Object.hasOwn()")}}
- {{jsxref("Array.prototype.forEach()")}}
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ for (const i in iterable) {
}

for (const i in iterable) {
if (iterable.hasOwnProperty(i)) {
if (Object.hasOwn(iterable, i)) {
console.log(i); // logs "0", "1", "2", "foo"
}
}
Expand Down Expand Up @@ -323,14 +323,14 @@ thorough explanation of how {{jsxref("Statements/for...in", "array iteration and

```js
for (const i in iterable) {
if (iterable.hasOwnProperty(i)) {
if (Object.hasOwn(iterable, i)) {
console.log(i); // logs 0, 1, 2, "foo"
}
}
```

This loop is similar to the first one, but it uses
{{jsxref("Object.prototype.hasOwnProperty()", "hasOwnProperty()")}} to check if the
{{jsxref("Object.hasOwn()", "hasOwn()")}} to check if the
found enumerable property is the object's own, i.e. not inherited. If it is, the
property is logged. Properties `0`, `1`, `2` and
`foo` are logged because they are own properties (**not
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ operator on a global variable.
```js
'use strict';
var x = 1;
globalThis.hasOwnProperty('x'); // true
Object.hasOwn(globalThis, 'x'); // true
delete globalThis.x; // TypeError in strict mode. Fails silently otherwise.
delete x; // SyntaxError in strict mode. Fails silently otherwise.
```
Expand All @@ -112,16 +112,14 @@ to a value, the scope chain is searched. This means that properties on the globa
are conveniently visible from every scope, without having to qualify the names with
`globalThis.` or `window.` or `global.`.

Because the global object has a `String` property (`globalThis.hasOwnProperty('String')`), you can use the following code:
Because the global object has a `String` property (`Object.hasOwn(globalThis, 'String')`), you can use the following code:

```js
function foo() {
String('s') // Note the function `String` is implicitly visible
}
```

```

So the global object will ultimately be searched for unqualified identifiers. You don't
have to type `globalThis.String`, you can just type the unqualified
`String`. The corollary, in non-strict mode, is that assignment to
Expand All @@ -130,7 +128,7 @@ scope chain, assume you want to create a property with that name on the global o

```js
foo = 'f' // In non-strict mode, assumes you want to create a property named `foo` on the global object
globalThis.hasOwnProperty('foo') // true
Object.hasOwn(globalThis, 'foo') // true
```

In ECMAScript 5, this behavior was changed for [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode).
Expand Down