LoginSignup
25
25

More than 5 years have passed since last update.

JavaScriptでかっこよくthisを回避する

Posted at
var a = {
    f: function() {
        // do something
    }
};

こんな感じのオブジェクトがあるとき、

a.f.call(null);

こんなコードを書くことがあります。Function#call()メソッドを使ってa.f()の中でthisaになるのを避けているんですけど、わりとダサイ感じです。

(0, a.f)();

こうすることで同じことができることに気づいたのでメモ。

('unset this', a.f)();

これだとコードの意図も書いておけて、なんかかっこいい気がしました。タイプ数増えちゃいますけど。

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