Last Updated: February 25, 2016
·
793
· 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]

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside