ES2015: call method from the construcror

I need the DOM element be added to some container when the new instance of ES2015 class created. Looks like it’s impossible to call the method from the constructor.

let titleCounter = 0;

  class Header{


      titleCounter++; = 'title'+titleCounter;
      this.html = `
        <div class="${}" style="background-color: blue;">Title</div>

     //addDOMtoField(); // don't work

  let instance1 = new Header();
  min-height: 5px;
  background-color: green;
  padding: 5px;
  color: white;
<script src=""></script>
<div id='container'>

Something more elegant than add $('#container').append(this.html); to the constructor?


In JavaScript, class field and method names aren’t available as variable name bindings in the constructor and other methods; they can only be accessed through a reference to the instance, which can be obtained through this.

So, you have to use this.addDOMtoField() instead of just addDOMtoField().

Leave a Reply

Your email address will not be published. Required fields are marked *