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); };
}
It will recognize all of the scripts in the document first, before assigning values to carry over variables. Thus it is necessary to declare the variable without a value, so that the initialization does not replace the values. In general it is also good house keeping to declare all of your variables at the top.
Variables are containers for storing data values. Unlike other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.
Each variable has a name, which you choose, and subsequently use to refer to it. You must start by declaring the variable, this gives the variable a name and reserves some memory space to store whatever value the variable takes. It also tells the compiler what you intend the variable to represent.
Definition: A variable is a holder for a representation of a value. A variable does have location in time and space. Also, variables, unlike values, can be updated; that is, the current value of the variable can be replaced by another value.
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.
"this" refers to the current "object". The power resides, when talking about javascript, into the fact that the "this" expression is evaluated context-wise, so for example if a method is executed in another object context, the "this" value will change respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With