Last Updated: February 25, 2016
·
582
· abe33

Object factory in JavaScript

Actually there's no easy way to instantiate an object with a constructor function and an array of arguments for the constructor.

This is a little snippet that defines a build function that allow you to do that:

cache = {}
build = (ctor, args) ->
  f = if cache[args.length]?
    cache[args.length]
  else
    argumentsSignature = ("arg#{n}" for n in [0..args.length-1]).join(',')
    cache[args.length] = new Function "ctor,#{argumentsSignature}", "return new ctor(#{argumentsSignature});"
  f.apply null, [ctor].concat(args)

Now, given a class Foo such as:

class Foo
  constructor: (a,b) ->
    console.log(a,b)

You can do:

build Foo, [10,20]