Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding code to a javascript function programmatically

People also ask

How do you extend a function in JavaScript?

Use extendFunction. init = extendFunction(init, function(args) { doSomethingHereToo(); }); But in your specific case, it's easier to extend the global onload function: extendFunction('onload', function(args) { doSomethingHereToo(); });

Can we add properties to function in JavaScript?

Read this article: packtpub.com/article/using-prototype-property-in-javascript You cannot add a property x to a function fn like so: fn. x = 'something'. You need to use prototype.


If someFunction is globally available, then you can cache the function, create your own, and have yours call it.

So if this is the original...

someFunction = function() {
    alert("done");
}

You'd do this...

someFunction = (function() {
    var cached_function = someFunction;

    return function() {
        // your code

        var result = cached_function.apply(this, arguments); // use .apply() to call it

        // more of your code

        return result;
    };
})();

Here's the fiddle


Notice that I use .apply to call the cached function. This lets me retain the expected value of this, and pass whatever arguments were passed in as individual arguments irrespective of how many there were.


first store the actual function in a variable..

var oldFunction = someFunction;

then define your own:

someFunction = function(){
  // do something before
  oldFunction();
  // do something after
};

You can make a function that calls your code, and then calls the function.

var old_someFunction = someFunction;
someFunction = function(){
    alert('Hello');
    old_someFunction();
    alert('Goodbye');
}

I don't know if you can update the function, but depending on how it is referenced, you can make a new function in its place:

var the_old_function = someFunction;
someFunction = function () {
    /* ..My new code... */
    the_old_function();
    /* ..More of my new code.. */
}