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); };
}
In order to latch onto the variable as part of a closure.
For example:
The specific example you wrote does not need a closure if you invoke the method in the expected way:
However, it’s possible to ‘break’ it like so:
Your code using the closure, on the other hand, is safe against this sort of tomfoolery.