views:

9900

answers:

5

(The answer to this, if there is one, is probably out there already, but I lack the proper terminology.)

I have a function, a(), that I want to override, but also have the original a() be performed in an order depending on the context. For example, sometimes when I'm generating a page I'll want to override like this:

function a()
{
  new_code();
  original_a();
}

and sometimes like this:

function a()
{
  original_a();
  other_new_code();
}

How do I get that original_a() from within the over-riding a()? Is it even possible?

(Please don't suggest alternatives to over-riding in this way, I know of many. I'm asking about this way specifically.)

+2  A: 
var org_a = window.a;

function a(){
   org_a();
   other_new_code();
}

From the back of mye head, but it should do the trick.

krosenvold
+14  A: 

You could do something like this:

var a = (function() {
    var original_a = a;

    if (condition) {
        return function() {
            new_code();
            original_a();
        }
    }
    else {
        return function() {
            original_a();
            other_new_code();
        }
    }
})();

Declaring original_a inside an anonymous function keeps it from cluttering the global namespace, but it's available in the inner functions.

Matthew Crumley
Thanks! That's very helpful.
Kev
+1  A: 

i think this link Proxy pattern from the jquery site might help you

PhilHoy
+1  A: 

Thanks guys the proxy pattern really helped.....Actually I wanted to call a global function foo.. In certain pages i need do to some checks. So I did the following.

//Saving the original func

var org_foo = window.foo;

//Assigning proxy fucnc

window.foo = function(args){

   //Performing checks

   if(checkCondition(args)){

     //Calling original funcs

     org_foo(args);
   }
};

Thnx this really helped me out

Naresh S
A: 

You can override a function using a construct like:

function override(f, g) { return function() { return g(f); } }

For example:

a = override(a, function(original_a) {

     if (condition) { new_code(); original_a(); }
     else { original_a(); other_new_code(); }
});
Hai Phan