LoginSignup
5
1

More than 5 years have passed since last update.

Babel6系でextendsしたクラスにinstanceofを使う方法

Last updated at Posted at 2017-11-14

確認したバージョン

babel-core v6.26.0
babel-plugin-transform-builtin-extend v1.1.2

babel6系でコンパイルするとinstanceofが正しく効かない

class CustomError extends Error {};

console.log(new CustomError() instanceof Error);       // true
console.log(new CustomError() instanceof CustomError); // false!!!

原因

英語ダメなので詳しく読めてないですが、6系のバグの様です。
https://github.com/babel/babel/issues/3083

回避方法

1.prototype上書き

class CustomError extends Error {};
CustomError.prototype = Error.prototype; // ここ!

console.log(new CustomError() instanceof Error);       // true
console.log(new CustomError() instanceof CustomError); // true♪

※色々試してみたのですが、なぜこれで直るのかまでは追えませんでした、、、教えて偉い人!

2.プラグインを入れる

babel-plugin-transform-builtin-extend
.babelrc

{
    "plugins": [
        ["babel-plugin-transform-builtin-extend", {
            globals: ["Error", "Array"]
        }]
    ]
}

まとめ

  • babel6系で、extendsしたクラスにinstanceofをかけても正しく動かない
  • 上記の回避方法を2つ紹介
  • 個人的には方法1で対象のissueのリンクを貼るのを採用

参考リンク

余談

babelのバグなので、chromeで直接実行すると意図通りに動くことを確認できます。
image.png

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1