Tuesday, 27 August 2013

Send a constructor as a parameter

Send a constructor as a parameter

One of the nice things in Javascript is the ability to send functions as
parameters. I have an application where I have to send classes as
parameters.
As a simple example, I need a function that makes some tests on a class,
and I want to send the class as a parameter:
test(ClassA);
test(ClassB);
where ClassA and ClassB are two different classes.
A 1st possible solution is:
function test(theClass) {
var object1 = new theClass();
var object2 = new theClass();
assert(object1.toString()===object2.toString());
// ... more asserts ...
}
This works well but it doesn't allow me to send parameters for
constructing the classes. For example, ClassA may have several
iniialization options, and I may want to test each option separately.
A 2nd possible solution is:
function test(theClass, theInitializationOptions) {
var object1 = new theClass(theInitializationOptions);
var object2 = new theClass(theInitializationOptions);
assert(object1.toString()===object2.toString());
// ... more asserts ...
}
Which I can use like this:
test(ClassA, {option1: 1, option2: 2...});
test(ClassA, {option1: 2, option2: 3...});
test(ClassB, {});
This works well, but it is cumbersome - it requires me to send two
parameters, and if the function "test" uses sub-functions, it will have to
send these two parameters all the way down. I am looking for a function
'test' that takes only one parameter.
A 3rd possible solution is to send an initialization function instead of a
class:
function test(theClassConstructor) {
var object1 = theClassConstructor();
var object2 = theClassConstructor();
assert(object1.toString()==object2.toString());
}
Which I can use like this:
test(function() { return new ClassA(1,2,3); }) /* test class A */
test(function() { return new ClassB(4,5); }) /* test class B */
The problem is that this 'test' function takes a function instead of a class.
I am looking for a function 'test' that will take a class as an argument
(i.e. it will initialize a new object with the "new" operator), but still
allow the caller to pass arguments together with the class.
In other words, I am looking for a way to bind arguments with a constructor.
Is this possible in Node.js?

No comments:

Post a Comment