I am attempting to pass function scope to a callback method. The problem I am having is that I am getting object scope, which does not provide me with access to the parameters and local variables in the original function. My understanding of "this" means the current context (whether it be window or some object) in addition to locally declared variables and parameters. [cite Richard Cornford's excellent work at http://jibbering.com/faq/notes/closures/ on "Execution Contexts" section]. I also understand that variables in JavaScript have function scope (that if they are declared inside a function, they are only accessible from within that function).
With that understanding, in a new environment, I am trying to code a pattern that I did alot for my previous employer, calling to an asynchronous method, specifying a callback handler and passing my current scope, expecting it to be available in the callback method. I am not finding this to be the case in my current environment. (disclosure: i was using ExtJS in my previous environment... making me feel now like I was a bit too cozy w/ the framework, making assumptions about what was going on).
My simple test code demonstrates what I am trying to do and what does not work.
function myHandler(data, ctx) {
console.log('myHandler(): bar: ' + bar); // <- prob: bar undefined
console.log(JSON.stringify(data));
}
MySvcWrap = {
doWork: function(p1, callback, scope) {
var result = {colors: ['red', 'green'], name:'Jones', what: p1};
if (callback) {
callback.call(scope||this,result, scope);
}
}
}
function lookup() {
var bar = 'food'; // local var
MySvcWrap.doWork('thang', myHandler, this); // scope object is this
}
lookup();
The problem here is that the 'this' passed to MySvcWrap.doWork is the Window global object in this case. My intention is to pass function's execution context to myHandler.
What I have tried. If, instead of 'this', I pass an object, that works, e.g.:
function myHandler(data, ctx) {
console.log('myHandler(): this.bar: ' + this.bar); // <- no prob: this.bar
console.log(JSON.stringify(data));
}
function lookup() {
var bar = 'food'; // local var
MySvcWrap.doWork('thang', myHandler, {bar: bar}); // scope object is just object
}
I need someone to club me over the head here... when passing 'this' in my first case, of course this is the global scope (I am in a globally defined function)... My problem is that I thought when passing scope that I had access to locally defined variables and parameters w/in that context... Am I rocking my previous understanding of JS?? How to accomplish this task?