勘違いしがちなケース

以下の関数呼び出しのthisは一見するとobjを指すように思えるが、実際は前述の「パターン1」の呼び出しであるためthisはGlobalObjectを指す。

var obj = { testMethod: function() {
    var func = function(){ console.log(this); };
    func();
} };

obj.testMethod();    // ... thisは、GlobalObject(通常はwindowオブジェクト)

この問題は、慣例として以下のように記述することで回避することが多い。

var obj = { func: function() {
    var self = this;
    var func = function(){ console.log(self); };
    func();
} };

obj.testMethod();    // ... thisは、obj