Thomas Strobl
Thomas Strobl

Reputation: 154

What is the best practice to add functions to a function in JavaScript?

I have an occurence where I want to have a main js-file with one resize function and specific files that can add workload to the main file without changing the mainfile and manually calling functions.

Lets say I have an object literal

var App = {
  resize: function(){
    // Code should be executed here
  },
  addResize: function(){
    // ?
  }
}

and I want a function to add code to the resize function which dynamically adds workload to the resize function (which gets called on window resize):

App.addResize(function(){ ... });

The first thing that came to my mind is to store the anonymous functions from addResize to an array and iterating over it in the resize function, but that doesn't feel like doing a best-practice:

var App = {
  resizeFunctions = [];
  resize: function(){
    // iterate over resizeFunctions and call each one
    // here I define throttling/debouncing ONCE
  },
  addResize: function(fn){
    this.resizeFunctions.push(fn);
  }
}

window.onresize = App.resize();

App.addResize(fn1);
App.addResize(fn2);

Is there a better way?

Upvotes: 1

Views: 268

Answers (4)

Rakesh Juyal
Rakesh Juyal

Reputation: 36749

You can treat your object literal as array.

App["resize"] = function(){
  //Code goes here
}

__

Or

App.resize = function(){
//Code here
}

Both are equally good. These will update the definition of resize

If you want to add some new method, then too the same syntax will work.

App["myNewMethod"] = new function(){
 //Code here
}

Edit after OP's comment

var oldFun = App["resize"];   // or may be store this in App itself
App["resize"] = function(){
    //Pre-processing 

    // Now call original resize method
    oldFun();   //If resize method used method argument then use oldFun.apply( this, arguments );


    //Post processing 
}

Upvotes: 0

Trace
Trace

Reputation: 18869

as you are referring to one function, ie. a resize function, I assume that you are looking for function overloading:

Function overloading in Javascript - Best practices
http://ejohn.org/blog/javascript-method-overloading/

If you want to extend the functionality of a set of methods that are all related to a single parent-object into different child objects, I would look into prototypal inheritance.
It allows you to define re-define the parent methods for each of the child-objects.

Upvotes: 1

pstenstrm
pstenstrm

Reputation: 6489

App.addResize(function(){ ... });

would pass the function to addResize as an attribute but not add it to it. You could do

App.addResize.newFunction = function(){ ... };

Where newFunction is the name of the function

Upvotes: 0

WhiteFang
WhiteFang

Reputation: 199

Do you want to overwrite the existing function? Then you can just do this:

App.addResize = function(){}

Upvotes: 0

Related Questions