Design & Download
Your JS Library
in Seconds!!!

Snippet: apply() & call()

Written by Christopher West (cwest) on July 19, 2016.
Call functions in a different way. Mostly useful when chaining calls.
function apply(subject, fn, opt_args) {
  return (typeOf(fn, 'String') ? subject[fn] : fn).apply(subject, opt_args);
}
function call(subject, fn) {
  return apply(subject, fn, slice(arguments, 2));
}

apply(...) API Documentation

Calls the specified function with the specified arguments.

Parameters

  1. subject {*}:
    The object to call the function on.
  2. fn {Function|string}:
    If this is a string it will be converted to the function at subject[fn]. This is the function which will be called with the context being subject.
  3. opt_args {Array}:
    Optional. If specified these are the arguments that will be passed to the function with each top-level value in the array being passed as an argument.

Returns

The return value of the specified fn function.

call(...) API Documentation

Calls the specified function with the specified arguments.

Parameters

  1. subject {*}:
    The object to call the function on.
  2. fn {Function|string}:
    If this is a string it will be converted to the function at subject[fn]. This is the function which will be called with the context being subject.
  3. ...opt_args {*}:
    Optional. Each argument passed will be passed to fn.

Returns

The return value of the specified fn function.