Skip to content

Instantly share code, notes, and snippets.

@vishaltelangre
Last active December 28, 2015 20:49
Show Gist options
  • Save vishaltelangre/7559928 to your computer and use it in GitHub Desktop.
Save vishaltelangre/7559928 to your computer and use it in GitHub Desktop.
call function dynamically with indefinite # of arguments #js
function execFn( fn ) {
var context;
// check passed in 'this' a.k.a. 'arguments[0]' & set context
context = ( typeof this === "undefined" || typeof this === "null" )
? window
: this;
// locate 'fn' in 'context' or it's a raw function
fn = ( typeof fn === "function" )
? fn
: context[fn];
// pass on arguments and call the 'fn'
fn.apply( context, Array.prototype.slice.call( arguments, 1 ) ); // shift first and pass rest
};
// -------
// USAGE:
// -------
testFn = function (a,b) { console.log( a, b, "WOW!" ); }
obj = { locate: function( emoticon ) { console.log( this.secret, emoticon ); }, secret: "TREASURE" };
execFn( "testFn", "5", {a:2} ); // 5 Object WOW!
execFn( testFn, 7, {a:3} ); // 7, Object "WOW!"
execFn( "locate", ":-O" ); // TypeError: Cannot call method 'apply' of undefined
execFn.call( obj, "locate", ":-O" ); // TREASURE :-O
execFn.bind( obj )( "locate", ":-)" ); // TREASURE :-)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment