2

I'm using the following pattern for my class constructor:

function SomeConstructor(a){
    if (!(this instanceof arguments.callee)){
        return new arguments.callee(a);
    }
    //the constructor properties and methods here
}

This works well when I know the number of arguments I'm passing to the constructor. The problem is that in some cases I do not, when using inheritance, for example:

SomeConstructor.prototype = AnotherClass();

This is not as simple as looking up the definition of AnotherClass, since this logic is part of a framework and gets generated automatically. I tried to work around this by calling apply method on the arguments.callee, but receive the following error:

function apply() { [native code] } is not a constructor

Passing arguments to callee directly won't work, since it's an array. Is there something similar to apply that works with constructors or a workaround that I'm not seeing here?

Also, this is an internal framework, so I can tweak what the constructor generates, the only requirements are:

  • we must be able to instantiate classes without the use of new keyword from outside
  • classes have to be inheritable such that the child constructor may not be aware (at compile time) of all the arguments that the parent receives
  • class initialization has to be in Class(a, b, c) format, I can't wrap the arguments in an array

EDIT: The code I tried for apply sequence looked as follows:

function SomeConstructor(){
    if (!(this instanceof arguments.callee)){
        return new arguments.callee.apply(arguments);
    }
    //the constructor properties and methods here
}
Alexander Tsepkov
  • 3,946
  • 3
  • 35
  • 59
  • 1
    Please show the code you tried that caused that error. `apply` is probably the right answer, you just have to get the calling sequence correct. – Barmar Dec 26 '13 at 18:00
  • It seems to me that you're thinking of JavaScript too similarly to other languages. My main reasoning is that in JavaScript, there are no classes. Perhaps there's an entirely more natural way to handle this? – m59 Dec 26 '13 at 18:02
  • 1
    [do not use `new` for inheritance](https://stackoverflow.com/questions/12592913/what-is-the-reason-to-use-the-new-keyword-here)! Do not use the deprecated `arguments.callee`, but simple the functions name! – Bergi Dec 26 '13 at 18:05
  • I don't understand: if `AnotherClass` is part of a framework, how exactly do you manipulate it, to be callable as constructor without the `new` keyword? Do you wrap it into another function? – basilikum Dec 26 '13 at 18:38

0 Answers0