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

Time:06-17

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? thanks in advance

CodePudding user response:

Your constructor only captures the first argument, and since you didn't pass the array as argument, but spread it over different arguments, the constructor gets a string and ignores the other strings.

To make the comparison fair, you should define the constructor as follows:

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

CodePudding user response:

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.

  • Related