2

The following pattern is used a lot when building Polymer 2.0 ES6 web components.

constructor() {
  super();
}

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

However here in the Shop App the pattern is only followed 3 times, in the following elements: shop-app.html, shop-ripple-container.html, shop-tabs-overlay.html.

When do we need to call super()? When does this call need to be inside the constructor() function? And what are the consequences of not calling super() as appears in the case of the Shop app?

Edit: A user (@4castle) suggested this question might be a duplicate of this question. I respectfully disagree. This question deals with Polymer, whereas the other deals with React. The other question asks about arguments passed to the super() function. This question wants to know what happens when super() is not called and where the best place to call is (i.e., inside constructor() or not).

Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
  • Possible duplicate of [what does super() do with any arguments?](https://stackoverflow.com/questions/39822941/what-does-super-do-with-any-arguments) – 4castle Aug 02 '17 at 22:00
  • 1
    `super()` is required when a class `extends` another class. Otherwise, it will throw a `ReferenceError` if you try to access `this` without first calling `super()`. – 4castle Aug 02 '17 at 22:04
  • @4castle: I added and answer based on your comment and the other question you pointed to. I also edited the question to explain why I think it's different. Please let me know if you think I'm on the right track or not if you wouldn't mind. – Let Me Tink About It Aug 02 '17 at 22:44

2 Answers2

2

When do we need to call super()?

super() calls the constructor of the element's superclass (parent class). If an element's definition defines a class that extends another class and super() is not called explicitly, the element calls the constructor of the superclass by default.

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

The proper place to call super() is inside the element's constructor() method.

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

In the case where,

class MyElement extends Polymer.Element {...}

as in the case of the Shop App — the Polymer.Element constructor is called by default if super() is not called explicitly.

Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
2

In fact it's also good practice to invoke the following to get the full benefit of your super (parent):

ready() {
  super.ready();
}

That will invoke the ready function in Element when your component is ready.

Jason Rice
  • 446
  • 5
  • 8