Hello,
I am messing around with javascript. I am trying to create a function to which i can pass a constructor and recieve back an object. Kinda (read exactly) like the new keyword. call it a learning exercise. I have a working model but i don't like it. here it is
function CREATE(constructor) {
var o = new constructor();
if (arguments.length > 1) {
constructor.apply(o, Array.prototype.slice.apply(arguments, [1]));
}
return o;
}
I don't like it because it uses the new keyword on the constructor and then calls the constructor again if there are any arguments to be passed on it. kinda stupid. More importantly its not what i first wrote and since i don't understand why what i first wrote doesn't work, im agrivated. What I want is
function CREATE(constructor) {
var o = new Object();
o.prototype = constructor.prototype;
if (arguments.length > 1) {
constructor.apply(o, Array.prototype.slice.apply(arguments, [1]));
}
return o;
}
here is some test code to illustrate how this breaks....
function TestConstructor(value) {
this.value = this.dummy(value);
}
TestConstructor.prototype.dummy = function (value) {
return value;
};
var testObject = CREATE(TestConstructor, 1);
javascript says that dummy does not exists. I run it in firebug and just before the this.value = this.dummy(value);
line is run, this
is an object that has a prototype member and that prototype member has a dummy method. From what i understand, javascript should try to find dummy as a method of this
, fail, then look for it as a member of this.prototype
and succeed. I can see that it is there in firebug. Does anyone have any idea what is going on?
Thanks,
Aaron.