クロージャーの一部として変数にラッチするため。
例えば:
MyClass.prototype.doStuff = function(){
this.foundItems = [];
var self = this;
this.myString.replace(/.../,function(){
// `this` is actually the `window` inside this callback
// so we need to use `self` to invoke another method on our instance object
self.foundItems.push( self.doOtherStuff() );
});
};
あなたが書いた特定の例は、期待される方法でメソッドを呼び出す場合、クロージャを必要としません:
function Foo(){
this.array = [];
this.myFunc = function(){
return this.array;
}
}
var foo = new Foo;
foo.myFunc(); // []
ただし、次のように「分割」することは可能です。
var f2 = foo.myFunc;
f2(); // undefined, since `this` was the window
一方、クロージャーを使用するコードは、この種のばかげたことに対して安全です。