2

Is it possible to call the constructor using an arguments object?

var MyClass = function(a, b){
  this.a = a;
  this.b = b;
};
var myClassInstance = function(){
  //This line would not work, but is what I'm asking. Is there a way besides eval?
  return new MyClass.apply(?, arguments);
}('an A value', 'a B value');

2 Answers 2

7

Yes, you could do this:

var myClassInstance = function(){
  return MyClass.apply(Object.create(MyClass.prototype), arguments);
}('an A value', 'a B value');
2
  • 1
    This is not a very good answer in my opinion. Don't just post code, explain what it does, how it works, why you would do it, etc.
    – Dynamic
    May 11, 2012 at 22:31
  • It's important to note that new returns the create object automatically if not returned from the constructor. The following is more correct. function mynew(Klass, arguments){ var o = Object.create(Klass.prototype); return Klass.apply(o, arguments) || o }
    – Kevin Cox
    Jun 14, 2014 at 3:36
2

Yes it is.

However, I had to rewrite your code a bit, as the method you're currently using appears to put the function calls into the global scope.

function MyClass(a, b){
    this.a = a;
    this.b = b;
};

function myClassInstance(){

    //The apply function will apply MyClass attributes to this object.
    //The apply function itself returns nothing.
    MyClass.apply(this, arguments);
    console.log(this); //Should show the a and b variables

    return this;
}

new myClassInstance('an A value', 'a B value');
3
  • Viable way to do it, however for taking up less lines of code I used Raynos' variation. Thank you :)
    – Beanow
    Mar 24, 2012 at 16:19
  • @Beanow Fair enough. Remember that the apply function doesn't return anything though. Mar 24, 2012 at 19:03
  • True I used an extra statement to store the object so I can return it.
    – Beanow
    Mar 25, 2012 at 19:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.