2

Im currently getting into es6 and want to use the class pattern. But how come "this.hola" is undefined in "onResize()"?

class Ui {

constructor() {
    this.win = $(window);
    this.hola = 'hola';
    this.init();
}

init() {
    this.addListeners();
}

addListeners() {
    this.win.on('resize load', this.onResize);
}

onResize() {
    console.log(this.hola);
}

}

export default Ui;

user2952238
  • 669
  • 2
  • 10
  • 33
  • Ohh, common. You already had correct code in your previous question https://stackoverflow.com/questions/46935952/es6-class-this-addeventlistener – Yury Tarabanko Oct 30 '17 at 14:01
  • 1
    `this.onResize` is a function not attached to any object. It has no `this`. When it gets invoked later in response to an event, `this` is set by jQuery to the element that triggered the event. If you want to retain the value of `this`, bind the function or use the es6 "fat arrow". – meager Oct 30 '17 at 14:01
  • replace `onResize` to `const onResize = () => {...}` – Rajesh Oct 30 '17 at 14:02
  • 1
    Replace this `this.win.on('resize load', this.onResize.bind(this));` – dinindu Oct 30 '17 at 14:03
  • @Rajesh: Class fields are an experimental feature. No browser supports it yet. Your example would be wrong anyway since class fields are not qualified with `const`/`let` or `var`. – Felix Kling Oct 30 '17 at 17:12
  • @FelixKling my bad. Have been working with typescript lately so got confused. Will remove it. – Rajesh Oct 31 '17 at 04:18

0 Answers0