سؤال

Just wondering if there is anyway to fire some code when a function is called, without adding the code to the function, for example:

function doSomething(){
    //Do something
}

//Code to call when doSomething is called
هل كانت مفيدة؟

المحلول

You can wrap the function :

(function(){
   var oldFunction = doSomething;
   doSomething = function(){
       // do something else
       oldFunction.apply(this, arguments);
   }
})();

I use an IIFE here just to avoid polluting the global namespace, it's accessory.

نصائح أخرى

Well, yes, it's not actually hard to do. The crucial thing is that a function's name is just an identifier like any other. You can redefine it if you want to.

var oldFn = doSomething;
doSomething = function() {
    // code to run before the old function

    return oldFn.apply(this, arguments);

    // code to run after the old function
};

NB that it's better to do oldFn.apply(this, arguments) rather than just oldFn. In many cases it won't matter, but it's possible that the context (i.e. the value of this inside the function) and the arguments are important. Using apply means they are passed on as if oldFn had been called directly.

What about something like:

function doSomething(){
     doSomething.called = true;
}

//call?
doSomething();

if(doSomething.called) {
   //Code to call when doSomething is called
}

I know you said you don't want to modify the original function, but consider adding a callback. Then you can execute code based on different results in your function (such as onSucess and onError):

function doSomething(onSuccess, onError){
    try {
        throw "this is an error";
        if(onSuccess) {
            onSuccess();
        }
    } catch(err) {
        if(onError) {
            onError(err);
        }
    }
}

Then, when you call doSomething, you can specify what you want done with inline functions:

doSomething(function() {
    console.log("doSomething() success");
}, function(err) {
    console.log("doSomething() error: " + err);
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top