So, I have read everything I can find about scoping, and fundamentally I know how it works. I have not seen anywhere that talks about which design choice is better, hence this thread.
Take the following example:
Code:
myClass = Ext.extend(Ext.someClass, {
constructor:function(){
//init
},
loadData:function(){
//do some loading
},
run:function(){
Ext.Ajax.request({
url:"someFunction.php",
success:function(response){
//call loadData()
}
});
}
});
Now, long story short, in the success callback of the Ajax.request I want to call myClass's loadData() method. There are 2 ways (that I have been using at random) to do this:
Use scoping. make the scope of the callback the scope of myClass and access loadData() though this.
Code:
run:function(){
Ext.Ajax.request({
url:"someFunction.php",
scope:this,
success:function(response){
this.loadData();
}
});
}
Use local vars. Cache this in a variable and use that to access loadData();
Code:
run:function(){
var self = this;
Ext.Ajax.request({
url:"someFunction.php",
success:function(response){
self.loadData();
}
});
}
Both do what I need to do. I have a general idea of the ramifications of both, but to be honest I am sure I am missing something:
Scoping:
Plus: No local vars to take memory.
Plus: No local vars to possibly get overwritten, etc.
Plus: Seems like it would also avoid some sort of circular reference that the GC might have a hard time with, but i don't know on this one.
Minus: Destroys the scope of the callback.
Minus: Harder to read, possibly maintain
Minus: Can get confusing with multiple levels of scope passing. I think the 'worst' I have is 3 levels of passing the scope down.
Variable:
Basically the opposite of scoping.
Is there a "recommended" or "approved" way of doing this? In the Ext codebase I see examples of both.