Skip to content

Commit 8c4976b

Browse files
aduh95RafaelGSS
authored andcommitted
doc: add a section regarding instanceof in primordials.md
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>
1 parent a5d959b commit 8c4976b

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

doc/contributing/primordials.md

+46
Original file line numberDiff line numberDiff line change
@@ -775,3 +775,49 @@ const proxyWithNullPrototypeObject = new Proxy(objectToProxy, {
775775
});
776776
console.log(proxyWithNullPrototypeObject.someProperty); // genuine value
777777
```
778+
779+
### Checking if an object is an instance of a class
780+
781+
#### Using `instanceof` looks up the `@@hasInstance` property of the class
782+
783+
```js
784+
// User-land
785+
Object.defineProperty(Array, Symbol.hasInstance, {
786+
__proto__: null,
787+
value: () => true,
788+
});
789+
Object.defineProperty(Date, Symbol.hasInstance, {
790+
__proto__: null,
791+
value: () => false,
792+
});
793+
794+
// Core
795+
const {
796+
FunctionPrototypeSymbolHasInstance,
797+
} = primordials;
798+
799+
console.log(new Date() instanceof Array); // true
800+
console.log(new Date() instanceof Date); // false
801+
802+
console.log(FunctionPrototypeSymbolHasInstance(Array, new Date())); // false
803+
console.log(FunctionPrototypeSymbolHasInstance(Date, new Date())); // true
804+
```
805+
806+
Even without user mutations, the result of `instanceof` can be deceiving when
807+
dealing with values from different realms:
808+
809+
```js
810+
const vm = require('node:vm');
811+
812+
console.log(vm.runInNewContext('[]') instanceof Array); // false
813+
console.log(vm.runInNewContext('[]') instanceof vm.runInNewContext('Array')); // false
814+
console.log([] instanceof vm.runInNewContext('Array')); // false
815+
816+
console.log(Array.isArray(vm.runInNewContext('[]'))); // true
817+
console.log(vm.runInNewContext('Array').isArray(vm.runInNewContext('[]'))); // true
818+
console.log(vm.runInNewContext('Array').isArray([])); // true
819+
```
820+
821+
In general, using `instanceof` (or `FunctionPrototypeSymbolHasInstance`) checks
822+
is not recommended, consider checking for the presence of properties or methods
823+
for more reliable results.

0 commit comments

Comments
 (0)