Why would you create a variable with value this
javascript, this
Solution
In order to latch onto the variable as part of a closure.
For example:
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() );
});
};
The specific example you wrote does not need a closure if you invoke the method in the expected way:
function Foo(){
this.array = [];
this.myFunc = function(){
return this.array;
}
}
var foo = new Foo;
foo.myFunc(); // []
However, it's possible to 'break' it like so:
var f2 = foo.myFunc;
f2(); // undefined, since `this` was the window
Your code using the closure, on the other hand, is safe against this sort of tomfoolery.
Problem
I've seen this done alot in JavaScript and I do remember finding out why but I can't remember the answer. I'm guessing it's something to do with scope and a function being called outside the "class" but why would one do this (preferably outlining an example): ``` function myClass () { var self = this; //... this.myArray = []; this.myFunc = function () { alert(self.myArray.length); }; } ```