Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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');
share|improve this question

2 Answers 2

up vote 4 down vote accepted

Yes, you could do this:

var myClassInstance = function(){
  return MyClass.apply(Object.create(MyClass.prototype), arguments);
}('an A value', 'a B value');
share|improve this answer
    
Ended up using this variation. Thank you. –  Beanow Mar 24 '12 at 16:17
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 '12 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 at 3:36

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');
share|improve this answer
    
Viable way to do it, however for taking up less lines of code I used Raynos' variation. Thank you :) –  Beanow Mar 24 '12 at 16:19
    
@Beanow Fair enough. Remember that the apply function doesn't return anything though. –  Jeffrey Sweeney Mar 24 '12 at 19:03
    
True I used an extra statement to store the object so I can return it. –  Beanow Mar 25 '12 at 19:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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