wrap a JavaScript method with a different method

Posted About 12 years ago. Visible to the public.

You can wrap a JavaScript method with another method by utilizing the apply() method and arguments property inside a function.

function wrapMethod(method) {
  var args = [];
  for(var i = 1; i < arguments.length; i++) {
    if(arguments[i] !== undefined) {
      args.push(arguments[i]);
    }
  }

  if(typeof this[method] !== 'undefined') {
    this[method].apply(this, args);
  }
}

You can call the method like this:

this.methodToWrap = function(one, two){
  console.log([one, two]);
}
wrapMethod('methodToWrap', 'hello', 'world');
Jonathan Knapp
Posted by Jonathan Knapp to Knowledge is Power! (2012-03-23 22:24)