Reputation: 22814
I'm aware that's it very common to use this
as much as possible when writing ActionScript 3
code (http://www.daveoncode.com/2009/01/07/we-should-always-use-actionscripts-this-keyword/).
But what should be done if you're writing anonymous functions, which don't have appropriate this
matching.
x.addEventListener(Event.WHATEVER, function(event:*) {
// When this callback fires, there is a fail:
// because there is no 'this' at this point.
// INVALID!
this.someAction();
});
I saw some recommendations on writing something like:
var self = this;
and then using self
in the code of your anonymous functions, but this seems weird.
What's your opinion on this question (for example, do you have something about it in your coding standard)?
Upvotes: 0
Views: 209
Reputation: 251
Do you have a specific reason for using anonymous functions over named functions? To quote Grant Skinner:
in almost every case, the use of an anonymous function in your code indicates an architectural problem. There are almost no real uses for anonymous functions – they are less efficient, much harder to debug, and far harder to grok when reading code.
Here is an interesting discussion about functions and scope from Mike Chamber's blog:
http://www.mikechambers.com/blog/2008/10/08/function-closures-and-this-in-actionscript-3/
If you scroll down near the bottom of the comments you can find Grant's response.
Upvotes: 1
Reputation: 4546
You can either use methods so "this" will be fixed to the instance, or stop using "this" so Flash Player will search the scope chain. I prefer letting Flash Player search the scope chain because I think code with "this" everywhere is hard to read.
Upvotes: 0
Reputation: 5386
Edited: Ah - my bad, I misunderstood. I typically don't refer to this
unless it's a self-contained action, etc. Using self
or something similar provides a means for other methods to access it. I personally approach development from this standard, for removing listeners, etc..
Hope that helps a little.
Upvotes: 0
Reputation: 2660
We have a similar approach (so this isn't an answer as much as it is affirmation of your approach):
public class myClass extends EventDispatcher{
public function foo() : void {
var thisObject : myClass = this;
this.addEventListener(EVENT, function(event : Event) : void {
thisObject.foo_internal();
}, false, 0, true);
}
protected function foo_interal() : void {
}
}
Of course, the purist might say that you shouldn't be adding listeners in a manner that prevents you from removing them! That said, we use this convention in other places where we use inner functions outside the context of a listener.
Upvotes: 0
Reputation: 16954
Since you're using anonymous function, there is no this (per se).
By defining self
you are defining a local scope variable that can be then called by reference... personally, I don't like the practice.
Upvotes: 1