LoginSignup
2
2

More than 3 years have passed since last update.

classインスタンスのメソッドに対して分割代入をすると、メソッド内でのthisの参照が失われるので注意

Posted at

知らずにちょっとハマったのでメモ。

ES6の分割代入を利用する際に、classのメソッドを分割代入するとthisへの参照が失われて、thisにundefinedがセットされてしまうようです。

そのため、メソッド内でthisを参照している場合エラーになります。

検証コード

check.js
console.log("--- test_class");

class DummyClass {
  constructor() {
    this.key = "value";
  }

  method() {
    console.log(this.key);
  }
};

const test_class = () => {
  const instance = new DummyClass();

  // これは問題ない
  instance.method();

  // これはエラーになる
  const { method } = instance;
  method();
};

test_class();

結果

$ node check.js
--- test_class
value
~/check.js:9
    console.log(this.key);
                     ^

TypeError: Cannot read property 'key' of undefined
    at method (~/check.js:9:22)
    at test_class (~/check.js:19:3)
    at Object.<anonymous> (~/check.js:22:1)

$ node -v
v12.13.1

感想

利用していたライブラリから返ってきた結果に対して分割代入をしていて、上記のエラーに遭遇しました。

ライブラリが返す結果がプレーンなオブジェクトなのか、クラスのインスタンスなのかを意識していないとこういうエラーに遭遇するので中々厄介だなと思いました。

何でもかんでも分割代入すれば良いというものでは無いですね...。

2
2
2

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
2
2