-1

When I call a method of an es6 class from a callback I can no longer refer to this as my object:

class store{
  constructor(){
    this.value = 10;
  };

  printValue(self){
    console.log(this);
    console.log(self);//the value that I want print
  };
};

class undefinedClass{
  constructor(store){
    this.store = store;
  };

  storeQuery(){
    let ff = this.store.printValue;
    setTimeout(ff, 300, this.store);
  };
};

let i = new store();
let b = new undefinedClass(i);
b.storeQuery();

When I call b.storeQuery() tha value that I want print is the second one. Is there a more elegant way for do that?

Fi3
  • 429
  • 6
  • 17
  • You do not seem to be passing the `self` parameter into `printValue`... what is it supposed to be equal to? – Tuvia Apr 19 '16 at 15:34
  • See also [How to access the correct `this` / context inside a callback?](http://stackoverflow.com/q/20279484/218196) – Felix Kling Apr 19 '16 at 17:22

2 Answers2

0

When you use an object's function reference in JavaScript, it will lose its ThisBinding being set to that object.

You can the ThisBinding to anything using Function.prototype.bind().

In this case you would use something like ff.bind(this.store).

alex
  • 479,566
  • 201
  • 878
  • 984
  • alex -- please see my comment here: http://stackoverflow.com/questions/36722798/this-self-in-es6-class#comment61030536_36722798 How do you address that? – Tuvia Apr 19 '16 at 15:37
  • Or use an arrow function. `printValue` expects an argument anyway. – a better oliver Apr 19 '16 at 15:43
0

As @alex say, with a .bind

The documentation is here

class store{
  constructor(){
    this.value = 10;
  };

  printValue(){
   
    console.log(this.value);//the value that I want print
  };
};

class undefinedClass{
  constructor(store){
    this.store = store;
  };

  storeQuery(){
    setTimeout(this.store.printValue.bind(this.store), 300);
  };
};


let i = new store();
let b = new undefinedClass(i);

 
b.storeQuery();
Jordane CURE
  • 99
  • 10