@@ -775,3 +775,49 @@ const proxyWithNullPrototypeObject = new Proxy(objectToProxy, { |
775 | 775 | }); |
776 | 776 | console.log(proxyWithNullPrototypeObject.someProperty); // genuine value |
777 | 777 | ``` |
| 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. |