PatS
PatS

Reputation: 11454

Javascript Passing variable arguments to superclass constructor

What is the best/recommended way to pass variable arguments to a superclass constructor? The background explains the problem I'm trying to solve.

Background

I'm porting some code from Java to Javascript. One of the coding patterns that Java has is function overloading. Java picks the best match to determine what function to call. This becomes interesting when the function is a Class constructor method.

So code in Java might be

public class MyParser extends Parser {
    public int parse(String str) { super(str); ... } 
    public int parse(String str, int base) { super(str, base); ... }
}

In Javascript becomes:

class MyParser extends Parser {
    constructor(){
        super(arguments); // THIS DOES NOT WORK
        if (arguments.length === 1 && typeof arguments[0] === 'string'){
            constructor_1arg(arguments[0]);
        } else if (...){
            constructor_2args(arguments[0], arguments[1]);
        }
    }
}

So I was wondering what is the best way to handle this case?

Possible solution

NOTE: I'm asking this because calling super() is a special case in a constructor and you can only call it once. So I didn't expect this to work but it did (in NodeJS v8.2).

class MyParserTry2 extends Parser {
    constructor(){
        console.log('MyParser2 passed ' + arguments.length + ' args. ', arguments);
        if (arguments.length === 1 && typeof arguments[0] === 'string'){
            super(arguments[0]);
            this.constructor_1arg(arguments[0]);
        } else if (arguments.length === 2 && typeof arguments[0] === 'string'){
            super(arguments[0], arguments[1]);
            this.constructor_2args(arguments[0], arguments[1]);
        }
    }

    constructor_1arg(arg1){ }
    constructor_2args(arg1, arg2){ }
}

I thought super() had to be called before other code, but this might be from another language. Does Javascript standard support calling super() as shown in this code snippet?

Previous answers/research

I searched StackOverflow for answers and found several similar questions but not this one. I found these questions or postings:

None of the above, however, answer my question.

So... What is the best/recommended way to pass variable arguments to a superclass constructor?

Upvotes: 9

Views: 8872

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138257

class SomeClass extends SomeSuperClass {
 constructor(...args){ super(...args); }
}

Using arguments is deprecated so you could rather use rest/spread operators.

Upvotes: 16

Related Questions