I need to store the reference to a constructor of a class in a variable and construct the object later. This is my minimal code example:
function A() {
var _foo = "A";
}
function Wrapper( constructorFunc ) {
var _constructorFunc = constructorFunc;
this.constructorFunc = function() {
return _constructorFunc;
}
}
var wrapper = new Wrapper( A.constructor );
var cFunc = wrapper.constructorFunc();
var obj = new cFunc(); /* obj should be an A now */
I hope it is clear what I would like to do. The Firebug console gives the error TypeError: cFunc is not a constructor
. What is the correct way?
Moreover I must be able to "compare" constructors, i.e. I need to know if two references point to the same constructor. (In C++ this would be possible, because one compares the function's address.) As an example:
function A() {
var _foo = "A";
}
function B() {
var _bar = "B";
}
function Wrapper( constructorFunc ) {
var _constructorFunc = constructorFunc;
this.constructorFunc = function() {
return _constructorFunc;
}
}
var wrapper1 = new Wrapper( A.constructor );
var wrapper2 = new Wrapper( A.constructor );
var wrapper3 = new Wrapper( B.constructor );
wrapper1.constructorFunc() == wrapper2.constructorFunc() /* should evaluate to true */
wrapper1.constructorFunc() == wrapper3.constructorFunc() /* should evaluate to false */
Is this possible?