开发者

Building an object on the fly and inject a variable

开发者 https://www.devze.com 2023-04-04 07:37 出处:网络
I am writing a JavaScript method that should do: C开发者_如何学Create an object of a type that has been passed as first argument,

I am writing a JavaScript method that should do:

  1. C开发者_如何学Create an object of a type that has been passed as first argument,
  2. put a variable into that new object and
  3. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消