Design & Download
Your JS Library
in Seconds!!!

Snippet: construct() - Apply Arguments To A Constructor

Written by Christopher West (cwest) on August 24, 2016.
Construct an object with an arbitrary number of arguments passed via an array (or an array-like object).
function construct(constructor, argList) {
  for (var argNames = '', i = argList.length; i--;) {
    argNames += (argNames ? ',a' : 'a') + i;
  }
  return Function(argNames, 'return new this(' + argNames + ')').apply(constructor, argList);
}

construct(...) API Documentation

Description

Constructs an object with an arbitrary number of arguments passed via an array (or an array-like object).

Parameters

  1. constructor {Function}:
    The constructor function.
  2. argList {Array|Arguments|Object}:
    The array or array-like object containing the arguments with which the object should be constructed.

Returns

Returns the result of calling new constructor(...argList).

Example

var arr = [2020, 10, 25, 5, 36, 52];
console.log(YourJS.construct(Date, arr));              // Wed Nov 25 2020 05:36:52
console.log(YourJS.construct(Date, arr.slice(0, -1))); // Wed Nov 25 2020 05:36:00
console.log(YourJS.construct(Date, arr.slice(0, -2))); // Wed Nov 25 2020 05:00:00
console.log(YourJS.construct(Date, arr.slice(0, -3))); // Wed Nov 25 2020 00:00:00