@uents blog

Code wins arguments.

関数の呼び出しパターンとthisの振る舞い

前回に引き続きJavaScriptのお勉強。

JavaScriptでよく議論になっているっぽいthisだけど、JavaScript: The Good Partsによると関数の呼び出しパターンによって振る舞いが異なるらしい。

というわけで試してみる。

パターン1:関数呼び出しパターン

thisはグローバルオブジェクトを指す。

var quo1 = function() {
    return this; // グローバルオブジェクトを返す
};
var quo1_this = quo1_get_this();  

nodeで実行。

> console.log(quo1_this);

// nodeのグローバルオブジェクトが出力される

パターン2:メソッド呼び出しパターン

thisはそのオブジェクトを指す。

var quo2 = {
    status: 2,
    get_this: function() {
        return this; // そのオブジェクトを返す    
    }
};
var quo2_this = quo2.get_this();

nodeで実行。

> console.log(quo2_this);
{ status: 2, get_this: [Function] }
undefined

パターン3:コンストラクタ呼び出しパターン

thisはnewで新規に作成されたオブジェクトを指す。

var Quo = function() {
    this.status = 3;
};
Quo.prototype.get_this = function() {
    return this; // newで作成されたオブジェクトを返す  
};
var quo3_this = (new Quo()).get_this();

nodeで実行。

> console.log(quo3_this);
{ status: 3 }
undefined

パターン4:apply呼び出しパターン

thisはapplyの引数で渡されたオブジェクトを指す。

var quo4 = {
    status: 4
};
// applyの引数に渡されたオブジェクトを返す               
var quo4_this = Quo.prototype.get_this.apply(quo4);

nodeで実行。

> console.log(quo4_this);
{ status: 4 }
undefined

まとめ

  • thisに何が入るかは関数が実行されるまでは決まっていない
  • thisは変数でもプロパティでもなく単なるキーワード