什么时候在 Polymer 2.0 中使用 constructor 和 super?

When to use constructor and super in Polymer 2.0?

在构建 Polymer 2.0 ES6 web 组件时经常使用以下模式。

constructor() {
  super();
}

Here the documentation describes calling the super(); function when defining an element.

However here in the Shop App 该模式只出现了 3 次,在以下元素中:shop-app.html、shop-ripple-container.html、shop-tabs-overlay.html .

我们什么时候需要调用super()?这个调用什么时候需要在 constructor() 函数内部?在 the Shop app 的情况下不调用 super() 的后果是什么?

编辑: 一位用户 (@4castle) 提出了这个问题 might be a duplicate of this question。我恭敬地不同意。这个问题涉及 Polymer,而另一个问题涉及 React。另一个问题询问传递给 super() 函数的参数。这个问题想知道当 super() 没有被调用时会发生什么以及调用的最佳位置在哪里(即是否在 constructor() 内)。

When do we need to call super()?

super() 调用元素的 superclass(父元素 class)的构造函数。如果一个元素的定义定义了一个扩展另一个 class 的 class 并且没有显式调用 super(),则该元素默认调用 superclass 的构造函数。

When does this call need to be inside the constructor() function?

调用 super() 的正确位置是在元素的 constructor() 方法中。

And what are the consequences of not calling super() as appears in the case of the Shop app?

在这种情况下,

class MyElement extends Polymer.Element {...}

与 Shop App 的情况一样 — 如果未显式调用 super(),则默认调用 Polymer.Element 构造函数。

事实上,调用以下内容以获得您的超级(父)的全部好处也是一种很好的做法:

ready() {
  super.ready();
}

这将在您的组件就绪时调用 Element 中的就绪函数。