【问题标题】:ES6 multiple inheritance?ES6 多重继承?
【发布时间】:2016-05-25 21:06:20
【问题描述】:

有人可以解释以下有效 ES6 代码的含义吗?

'use strict';

class first {
    constructor() {
    }
}

class second {
    constructor() {
    }
}

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

据我所知,JavaScript 中没有多重继承,但示例中显示的语法不会引发任何错误(在 Node.js 4.3.0 中),并且它可以工作,... - 怎么样我想了解什么,或者它在那里到底做了什么......

另外,我注意到如果我退出super() 调用,那么代码开始抛出错误ReferenceError: this is not defined

【问题讨论】:

  • @Tushar 那个问题是关于 Babel 的,这个问题是关于 ES6 的。
  • (first, second) 是逗号运算符,计算结果为 secondfirst 被扔掉了。
  • 这个问题与 Babel 无关。 Babel 只是一个工具/库,可以在浏览器不支持的情况下尽早使用 ES6。
  • @torazaburo 如果我们删除括号并只有first, second,Node.js 将拒绝此类代码,这纯粹是 Babel 语法。
  • 任何 ES6 处理器都会拒绝没有括号的代码。至于你最初的问题,只要看看 Babel 生成的 ES5 代码就应该清楚了。

标签: javascript node.js ecmascript-6


【解决方案1】:

这只是comma operator 的一个令人困惑的案例。

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

它不会抛出错误,因为它是有效的语法,但是它也不能工作,就像你所期望的那样。 third 只会继承自 second

我们可以通过编译为 ES5 语法来验证是否是这种情况,以检查它是否不会影响类定义。

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));

评估(first, second) 的结果作为_ref 传入,然后是third _inherits

【讨论】:

  • 你确定吗?如果我们注释掉super(),那么代码开始抛出错误:ReferenceError: this is not defined。但看起来确实只有second 是继承的。
  • 是的,我确定。查看编译后的 ES5 版本。
  • 这开始变得有意义了,尽管这真的很令人困惑,因为语法看起来如此。
  • 它并不比逗号运算符的任何其他用法更令人困惑。
猜你喜欢
  • 2019-01-25
  • 1970-01-01
  • 2017-11-25
  • 1970-01-01
  • 2010-09-27
  • 2012-03-07
  • 1970-01-01
相关资源
最近更新 更多