开发者

Object instantiation using eval in JavaScript

开发者 https://www.devze.com 2023-01-06 18:00 出处:网络
Short question, if this works (and it does): eval(\"new \" + generator.className + \"(\" + generator.constructorArgs.join(\", \") + \")\");

Short question, if this works (and it does):

eval("new " + generator.className + "(" + generator.constructorArgs.join(", ") + ")");  

why doesn't this work:

eval(generator.className + ".prototype.constructor.apply({}, generator.constructorArgs);");

The second expression always returns undefined, but in my opinion it should work. I tried it on dummy objects like:

var dummy = function () {};

Also, is there any way I can avoid using eval in this situ开发者_开发知识库ation?

Thanks,

Alex


Well, I think the problem is that your constructor function is not returning anything.

When you use the new operator, if the constructor function, does not return an object, the this value, which is the newly created object is returned implicitly, for example:

function Foo () {
  this.foo = 'bar';
}

new Foo(); // { foo: 'bar' }

If you invoke the function with call/apply, it will yield undefined, since there is no return value at all:

Foo.call({}); // undefined

So, the solution would be to return the this value on your constructor, e.g.:

function Bar() {
  this.bar =  'baz';
  //..
  return this;
}

Bar.call({}); // { bar: 'baz' }

Also, remember that using the new operator is not completely equivalent to apply a function using a new object as the this value, because when you use the new operator, the newly created object will inherit from its constructor's prototype, e.g.:

new Bar() instanceof Bar; // true
Bar.call({}) instanceof Bar; // false
0

精彩评论

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