1

Can somebody please explain the meaning of the following valid ES6 code?

'use strict';

class first {
    constructor() {
    }
}

class second {
    constructor() {
    }
}

class third extends (first, second) {
    constructor() {
        super();
    }
}

As far as I know, there is no multiple inheritance in JavaScript, but the syntax shown in the example doesn't throw any error (in Node.js 4.3.0), and it works,... - how is what I'm trying to understand, or what does it do there exactly...

Also, I noticed that if I comments out super() call, then the code starts throwing error ReferenceError: this is not defined.

vitaly-t
  • 22,286
  • 10
  • 106
  • 127
  • @Tushar that question was about Babel, this one is about ES6. – vitaly-t Feb 15 '16 at 03:47
  • 1
    `(first, second)` is the comma operator, and evaluates to `second`. `first` is thrown away. –  Feb 15 '16 at 03:49
  • That question is nor related to Babel. Babel is just a tool/library to use ES6 early when browsers are not supporting it. – Tushar Feb 15 '16 at 03:49
  • @torazaburo if we remove brackets and have just `first, second`, Node.js will reject such code, that's purely Babel syntax. – vitaly-t Feb 15 '16 at 03:52
  • Any ES6 processor would reject the code without the parens. As for your original question, just looking at the Babel-generated ES5 code should have made things clear. –  Feb 15 '16 at 03:54
  • The absence of `super` causing the ReferenceError is entirely unrelated to `(first, second)`. It is the behavior of **any** subclass. –  Feb 15 '16 at 03:57

1 Answers1

4

This is just a confusing case of the comma operator.

(1, 2) // 2
(1, 2, 3) // 3
(first, second) // second

It doesn't throw an error because it's valid syntax, however it doesn't work in the sense that you were expecting either. third will only inherit from second.

We can verify that this is the case by compiling to ES5 syntax to check that it's not affecting the class definition.

var third = (function (_ref) {
  _inherits(third, _ref);

  function third() {
    _classCallCheck(this, third);

    _get(Object.getPrototypeOf(third.prototype), 'constructor', this).call(this);
  }

  return third;
})((first, second));

The result of evaluating (first, second) is passed in as _ref, then third _inherits from it.

Dan Prince
  • 28,326
  • 12
  • 86
  • 115
  • Are you sure? If we comment out `super()`, then the code starts throwing an error: `ReferenceError: this is not defined`. But it does look like only the `second` one is inherited indeed. – vitaly-t Feb 15 '16 at 03:54
  • Yeah, I'm sure. Look at the compiled ES5 version. – Dan Prince Feb 15 '16 at 03:58
  • This starts making sense, although this is really confusing, for the way the syntax looks. – vitaly-t Feb 15 '16 at 04:01
  • It's no more confusing than any other use of the comma operator. –  Feb 15 '16 at 04:54