Created
September 16, 2015 19:47
-
-
Save amoilanen/f5d3336d64dc65c7c392 to your computer and use it in GitHub Desktop.
Demonstrates how constructor arguments can be expanded from an array in JavaScript when using 'new'.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Demonstrates how constructor arguments can be expanded if supplied as an array. | |
*/ | |
function createWithArgs(constructor, args) { | |
var boundArgs = [null].concat(args); | |
var boundConstructor = Function.prototype.bind.apply(constructor, boundArgs); | |
//When 'boundConstructor' is invoked with new, | |
//'this' will point to object being constructed, not 'null' | |
return new boundConstructor(); | |
} | |
/* | |
* Example of usage. | |
*/ | |
function Something(a, b, c) { | |
console.log('this inside the constructor = ', this); //Something{} | |
this.a = a; | |
this.b = b; | |
this.c = c; | |
} | |
var params = [1, 2, 3]; | |
var obj = createWithArgs(Something, params); | |
console.log(obj); // {a: 1, b: 2, c: 3} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment