0

How can I get "back to previous this? To explain better, I created this sample code:

class MyClass {
    constructor(x,y,z) {
    this.x = x;
    this.y = y;
        setTimeout(function () {
            this.z = z;
        }, 1000);
    }
}

var myVariable = new MyClass(10,15,20);

setTimeout(function () {
    console.log(myVariable.z);
}, 1500);

The problem is that last lane should output 20 but instead it gives me an error.

I understand why though. The this.z was understood as this of setTimeout(), not myClass, making myVariable.z as undefined.

How can I set this of myVariable inside my MyClass?

Kajcioch
  • 175
  • 1
  • 8

2 Answers2

1

Use an ES6 arrow function with lexical binding of this:

class MyClass {
    constructor(x,y,z) {
    this.x = x;
    this.y = y;
        setTimeout(() => {
            this.z = z;
        }, 1000);
    }
}

var myVariable = new MyClass(10,15,20);

setTimeout(function () {
    console.log(myVariable.z);
}, 1500);

Using this within an arrow function refers to the this of the surrounding code block (also called static scope).

See also: Do arrow functions not bind `this` inside ES6 classes?

Community
  • 1
  • 1
le_m
  • 19,302
  • 9
  • 64
  • 74
  • My app is Chromium-based, so this solution is perfect. Thanks a lot! I'll accept this answer as soon as I can. – Kajcioch Mar 27 '17 at 20:20
0

Your lambda function (closure) gets called asynchronously, so it does not run in object context. You may however save the reference in the upper context and use it in the closure.

e.g. var that = this; then that.z = z;