简体   繁体   中英

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?

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.

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 
}

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

App.addResize = function(){}
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM