1 | # @babel/plugin-transform-instanceof
|
2 |
|
3 | > Wraps `instanceof` expressions to allow constructors to customize the logic with a `Symbol.hasInstance` method
|
4 |
|
5 | ## Example
|
6 |
|
7 | **In**
|
8 |
|
9 | ```javascript
|
10 | foo instanceof Bar;
|
11 | ```
|
12 |
|
13 | **Out**
|
14 |
|
15 | ```javascript
|
16 | function _instanceof(left, right) {
|
17 | if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
18 | return right[Symbol.hasInstance](left);
|
19 | } else {
|
20 | return left instanceof right;
|
21 | }
|
22 | }
|
23 |
|
24 | _instanceof(foo, Bar);
|
25 | ```
|
26 |
|
27 | ## Installation
|
28 |
|
29 | ```sh
|
30 | npm install --save-dev @babel/plugin-transform-instanceof
|
31 | ```
|
32 |
|
33 | ## Usage
|
34 |
|
35 | ### Via `.babelrc` (Recommended)
|
36 |
|
37 | **.babelrc**
|
38 |
|
39 | ```json
|
40 | {
|
41 | "plugins": ["@babel/plugin-transform-instanceof"]
|
42 | }
|
43 | ```
|
44 |
|
45 | ### Via CLI
|
46 |
|
47 | ```sh
|
48 | babel --plugins @babel/plugin-transform-instanceof script.js
|
49 | ```
|
50 |
|
51 | ### Via Node API
|
52 |
|
53 | ```javascript
|
54 | require("@babel/core").transform("code", {
|
55 | plugins: ["@babel/plugin-transform-instanceof"]
|
56 | });
|
57 | ```
|
58 |
|
59 | ## References
|
60 |
|
61 | * [ES6 Spec: InstanceOf Operator Semantics](https://www.ecma-international.org/ecma-262/6.0/#sec-instanceofoperator)
|
62 | * [MDN: Symbol.hasInstance](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance)
|