Skip to content
Advertisement

Different behavior when extend natives class with constructor and passing arguments to super

Different behavior calling a constructor and without calling it, when creating an instance of an inherited class:

1Case when I pass constructor:

class MyArray extends Array {
    constructor(node) {
        console.log(node)
        super(node);
        console.log('nodes in constructor 1', node); // first
    }
};
let argument = ['first','second'];
let arr = new MyArray(...argument);

console.log(arr)// [first]

2Case when it happens automatically

class MyArray extends Array {};
let argument = ['first','second'];
let arr = new MyArray(...argument);

console.log(arr)// ['first', 'second']

There are different behavior Please tell me what is the difference, and why is this behavior observed?

Advertisement

Answer

In a subclass, the default constructor the JavaScript engine will supply if you don’t provide one looks like this:

constructor(...args) {
    super(...args);
}

Contrast that with your constructor (removing the console.log calls):

constructor(node) {
    super(node);
}

Notice how your version is only passing the first argument to super, but the default version passes all arguments to super.

That’s why you’re seeing the behavior you’re seeing, your constructor ignores everything but the first argument.

If you want to do something special with the first argument but still pass all arguments to super, you could use a rest parameter:

constructor(node, ...rest) {
    // ...do something with `node`...
    super(node, ...rest);
    // ...
}

Side note: Beware the weirdness that is the way the Array constructor handles its arguments, because what it does varies based on both the number and type of the arguments it receives:

  • If it receives only one argument that’s of type number, it creates an empty array with length set to that number.

  • If it receives multiple arguments, or a single argument whose type is not number, it puts the arguments in the array as elements.

When subclassing Array, you have to be careful to handle that…unusual behavior.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement