Search code examples
polymerpolymer-1.0polymer-2.x

What's the difference between an object initialised in the constructor vs properties


I have several mixins in a project I'm assigned too. Some have their objects set in the properties like:

static get properties() {
  return {
    config: {
      type: Object
    }
  }
}

While other mixins have their objects set in the constructor like:

constructor() {
  super();

  this.language = {
    name: "english",
    label: "EN"
  }
}

I guess both are globally accessible cause the mixins are loaded everywhere. But what's the difference between both implementations?

edit (additional code)

These mixins get created the following way:

MyMixin = function (superClass) {
  return class extends superClass {

    static get properties() {
      return {
        config: {
          type: Object
        }
      }
    }

    constructor() {
      super();
    }

or other method:

MyMixin = function (superClass) {
  return class extends superClass {

    static get properties() {
      return {
      }
    }

    constructor() {
      super();
      this.language = {
        name: "english",
        label: "EN"
      }
    }

and they are used by another component the following way:

class HomePage extends MyMixin(Polymer.Element) {
  ...
}

Solution

  • The ones created via Properties Object are mapped as HTML Attributes which means you can have a data binding for instance:

    <my-component config="[[someContent]]"></my-component>
    

    Variables created in constructor or connectedCallback are not mapped as HTML Attributes so you can not bind these from the outside.

    document.querySelector('my-component').language
    

    Will return

    {
      name: "english",
      label: "EN"
    }
    

    but

    document.querySelector('my-component').getAttribute('language')
    

    will return undefined and

    <my-component language="[[someContent]]"></my-component>
    

    wont work