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{

    constructor(){

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

     //addDOMtoField(); // don't work
     $('#container').append(this.html);
}   
      
addDOMtoField(){
    $('#container').append(this.html);
}
  }

  let instance1 = new Header();
#container{
  min-height: 5px;
  background-color: green;
  padding: 5px;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='container'>
  
</div>

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

Answer

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 *