Skip to content

Instantly share code, notes, and snippets.

@nulltier
Created February 7, 2017 21:48
Show Gist options
  • Save nulltier/2e4d6db364440b7fd4d1fb9246bd4ae3 to your computer and use it in GitHub Desktop.
Save nulltier/2e4d6db364440b7fd4d1fb9246bd4ae3 to your computer and use it in GitHub Desktop.
a way to call something as function withput potential runtime exception if you don't sure that thing is the function
/**
*
* @param {Function} fn - Function that should be run
* @param {Object} thisLink - This link should be set if fucntion should be call in the context of some object
* @param {...*} args - Any amount of arguments to be passed to the called function
*
* @comment args presented in the definition only for readability, there is no any other reason since it redefined right after the call
*/
runFunctionIfSafe: function(fn, thisLink, args) {
// stop doing whole thing if we don't get a function to call it later
if (typeof fn !== 'function') {
try {
// since some old desktop and some not so old mobile browsers have no support for such things
console.error('ARGUMENT ERROR: the first parameter should be the FUNCTION type');
} catch (e) {
// do nothing silently if console.error is not supported by the browser
}
return;
}
// safe handling of the provided this reference
thisLink = typeof thisLink === 'undefined' || typeof thisLink !== 'object' ? null : thisLink;
// skip first two arguments to exclude fn and thisLink from list with possible arguments
args = Array.prototype.slice.call(arguments, 2);
fn.apply(thisLink, args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment