0

i'm kinda new to es6 features, i'm trying to implement some basic class, like this

class App {
  constructor() {
    this.init();
  }

  init() {
    console.log("init!");
    this.hello();
  }

  hello(){
    console.log("Hello!");
  }
}

let app = new App;

everything works fine. this is my output:

init
Hello!

then i tried to implement the same thing with publish / subscribe pattern (using PubSubJs plugin):

class App {
  constructor() {
    PubSub.subscribe('say hello', this.init);
  }

  init() {
    console.log("init!");
    this.hello();
  }

  hello(){
    console.log("Hello!");
  }
}

let app = new App;

PubSub.publish('say hello');

This will call correctly the init method, but then will lose the class context when trying to call this.hello()

infact i get this output:

init //correct
Uncaught TypeError: this.hello is not a function //<- why this?

DEMO HERE

any idea? am i missing something? thanks

pumpkinzzz
  • 2,592
  • 2
  • 11
  • 28
  • 2
    You're passing down a method without the class necessarily having been instantiated. [Code pen with fixed version.][1]. Some useful articles to help understand `this` in JS: - http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/ - https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work [1]: https://codepen.io/nowy5/pen/NBKwGR?editors=0011 [2]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions [3]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind – nowy Jul 09 '18 at 13:23
  • thanks @nowy it works now :) – pumpkinzzz Jul 09 '18 at 13:36

0 Answers0