views:

231

answers:

1

It seems that "myFunction" in the following example loses its scope.

$().grep(myArray, myFunction)

By this, I mean that it no longer has access to the "this" of the scope it was defined in, and "this" becomes the window object. Can anyone explain why this is and if there's a handy way to preserve myFunction's scope? This javascript closure stuff halfway does my head in, but I'm trying to get facile with it.

+2  A: 
$.grep(myArray, function(){
    return myFunction.apply(realScope, arguments);
});

Replace "realScope" with the intended scope - what you want as the value of 'this'.

J-P
cool. thanks JimmyP
morgancodes