Design & Download
Your JS Library
in Seconds!!!

Snippet: func() - Create A Function with Context

Written by Christopher West (cwest) on August 24, 2016.
Create a function with a specified context.
function func(arrArgs, strBody, opt_objContext, opt_name) {
  var k, fn, arrContextVars = [], arrContextArgs = [];
  for (k in opt_objContext || {}) {
    if (has(opt_objContext, k) && isValidVarName(k)) {
      arrContextVars.push(k);
      arrContextArgs.push(opt_objContext[k]);
    }
  }
  return eval('(function(f,a){return function ' + ((opt_name != undefined && isValidVarName(opt_name)) ? opt_name : '') + '(){return f.apply(this,a.concat([arguments]))}})')(
    Function(
      arrContextVars.join(','),
      'return(function(' + arrArgs.join(',') + '){' + strBody + '}).apply(this,arguments[arguments.length-1])'
    ),
    arrContextArgs
  );
}

func(...) API Documentation

Description

Creates a function with a specified context.

Parameters

  1. arrArgs {Array.<string>}:
    The names of arguments.
  2. strBody {string}:
    The body of the function as a string.
  3. opt_objContext {Object}:
    Optional. If specified, the properties of this object whose names are valid variable names will be accessible by the function.
  4. opt_name {string}:
    Optional. If specified and is a valid variable name it will be used as the returned function name.

Returns

Returns a function where arrArgs are the argument names, strBody is the body of the function, the opt_objContext properties can be directly accessed by the function and opt_name is the name of the function.

Example

console.log(YourJS.func(['a','b'], 'return !typeOf(a,b)', YourJS, 'isNotOfType'));