DEV Community

loading...

Discussion on: What the beep is 'this' in JavaScript

Collapse
beitist profile image
Sebastian Stüwe

Hi Brit,

sorry for the late response - I couldn't exactly remember where it happened, but now I found the problem:

Assume the following micro-example:

START_NODE = document.getElementById('start');

class Major {
  constructor() {
    this.minor = new Minor();
    this.handler = '';
  }

  initHandler() {
    this.handler = new Handler();
  }

  listenToHandler(parameter) {
    this.minor.someValue = parameter;
  }

}

class Minor {
  constructor() {
    this.someValue = '';
  }
}

class Handler {
  constructor() {
    this.button = document.createElement('button');
    this.button.innerText = 'Click!';
    this.button.addEventListener('click', major.listenToHandler.bind(3));
    START_NODE.appendChild(this.button);
  }
}

let major = new Major();
major.initHandler();
Enter fullscreen mode Exit fullscreen mode

Here's a possible corresponding html-file:

<!DOCTYPE html>
<html>
  <head>
    <script src='bindproblem.js' defer></script>
  </head>
  <body>
    <div id='start'></div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

You'll notice that JS throws a TypeError which must have something to do with the scope, I presume. I've usually found workarounds, but I do not like them. I'd like to really understand the problem.

Thanks!
Sebastian.

Thread Thread
brityhemming profile image
Brit Hemming Author

This is likely a scope issue. A couple of things to know about classes:

  • classes are not hoisted - that means if we are putting our information above a class we have referenced it will not work
  • they use strict - it prevents window binding, forces us to write cleaner code with errors if we do not
  • Methods are a special syntax
  • A constructor function is visible

In your case point 1 is the issue - classes are not hoisted. You've created Handler below where you are invoking it.

Here's a codepen where I explain classes a little deeper. Hopefully that's helpful :)

codepen.io/BritHemming/pen/WNvYJMr