Timothy J Snyder

Apr
15

Optional Argument Constructors in JavaScript

Dynamic instantiation of JavaScript objects that have optional arguments can be tricky. I ran into the need for this a little while ago and came up with a solution that solves this problem.

The output of the first part of the script is:

in MyType(), args 0: foo 1: 1 2: 2 3: 3 4: 4 in f(), val = foo

Variable a shows a simple way in how to instantiate the MyType object through the arguments variable.

If you need a more dynamic way to instantiate the object, variable b shows how this can be done with the object.apply method.

in MyType(), args 0: bar 1: 1 2: 2 3: 3 in f(), val = bar