I am writing a JavaScript method that should do:
- C开发者_如何学Create an object of a type that has been passed as first argument,
- put a variable into that new object and
- call the method __construct of that object and pass the arguments to it passed to this method (except for the first).
Example usage:
this.create('Foo', 'bar', 42);
Should do:
var O = new Foo;
Foo.Application = this;
Foo.__construct('bar', 42);
What I have now:
Application.prototype.create = function(sType)
{
var Self = this;
eval('var Object = new ' + sType + ';');
// what to write here?
var aParameters = Array.prototype.slice.call(arguments, 1);
Object.__construct.apply(aParameters);
}
I tried to inject the Application var into the new object with the following codes:
Object.Application = this;
or:
var Self = this;
$.extend(Object, { Application: eval(Self) });
But in the __construct method this.Application is still undefined.
You do the sensible thing and change the API to accept a constructor function instead of a string.
app.create(Foo, args, moreargs);
Application.prototype.create = function _create(klass) {
var o = new klass();
o.Application = this;
o.__construct.apply(o, Array.prototype.slice.call(arguments, 1));
};
The reason why your code is broken is because your a) using eval
. Don't do that.
And you b) thought Object
was a good variable name when we have a global object constructor called Object
.
精彩评论