Skip to content

Commit

Permalink
doc: add a section regarding instanceof in primordials.md
Browse files Browse the repository at this point in the history
PR-URL: #50874
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
  • Loading branch information
aduh95 authored and RafaelGSS committed Nov 27, 2023
1 parent c1d68f7 commit f63fd8e
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions doc/contributing/primordials.md
Original file line number Diff line number Diff line change
Expand Up @@ -775,3 +775,49 @@ const proxyWithNullPrototypeObject = new Proxy(objectToProxy, {
});
console.log(proxyWithNullPrototypeObject.someProperty); // genuine value
```

### Checking if an object is an instance of a class

#### Using `instanceof` looks up the `@@hasInstance` property of the class

```js
// User-land
Object.defineProperty(Array, Symbol.hasInstance, {
__proto__: null,
value: () => true,
});
Object.defineProperty(Date, Symbol.hasInstance, {
__proto__: null,
value: () => false,
});

// Core
const {
FunctionPrototypeSymbolHasInstance,
} = primordials;

console.log(new Date() instanceof Array); // true
console.log(new Date() instanceof Date); // false

console.log(FunctionPrototypeSymbolHasInstance(Array, new Date())); // false
console.log(FunctionPrototypeSymbolHasInstance(Date, new Date())); // true
```

Even without user mutations, the result of `instanceof` can be deceiving when
dealing with values from different realms:

```js
const vm = require('node:vm');

console.log(vm.runInNewContext('[]') instanceof Array); // false
console.log(vm.runInNewContext('[]') instanceof vm.runInNewContext('Array')); // false
console.log([] instanceof vm.runInNewContext('Array')); // false

console.log(Array.isArray(vm.runInNewContext('[]'))); // true
console.log(vm.runInNewContext('Array').isArray(vm.runInNewContext('[]'))); // true
console.log(vm.runInNewContext('Array').isArray([])); // true
```

In general, using `instanceof` (or `FunctionPrototypeSymbolHasInstance`) checks
is not recommended, consider checking for the presence of properties or methods
for more reliable results.

0 comments on commit f63fd8e

Please sign in to comment.