passing a function from a class with the scope

This with functions

Within a function, the value of this depends on how the function is called.

If in Strict mode, then the value of this is undfined. If not in strict mode, this will default to the global object, which is window in a browser.

The issue

When extracting out the function into the new variable, the original object is lost.

Use bind to solve the issue

Using bind will allow you to set the this value.

const appDiv = document.getElementById('app');

class a {
  b = 5;

  getB() {
    return this.b;
  }
}

const obj = new a();
const aa= obj.getB.bind(obj);

appDiv.innerHTML = aa();
<div id="app"></div>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top