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:

JavaScript

2Case when it happens automatically

JavaScript

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:

JavaScript

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

JavaScript

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:

JavaScript

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