2

I’m trying to access “helperFunction” from inside a function in “steps” array. Obviously using “this” doesn’t refer to the correct object but I can’t seem to work out the proper solution.

const bannerAnimation = {
    property: 0,
    steps: [
        function one() {
            this.property = this.helperFunction();
        },
        function two() {
            console.log(this);
        }
    ],
    helperFunction() {
        // do some calculations and return the result
        return 1;
    },
    doSteps(steps = this.steps) {
        steps.forEach(step => {
            setTimeout(step, 100);
        });
    }
};

bannerAnimation.doSteps();

All help much appreciated!

abiadi
  • 27
  • 3
  • 1
    Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – evolutionxbox Jan 21 '20 at 11:08

1 Answers1

2

You can achiever this by using bind inside the callback to setTimeout to correctly bind the this to the correct context.

const bannerAnimation = {
    property: 0,
    steps: [
        function one() {
            this.property = this.helperFunction();
        },
        function two() {
            console.log(this);
        }
    ],
    helperFunction() {
        // do some calculations and return the result
        return 1;
    },
    doSteps(steps = this.steps) {
        var self = this;
        steps.forEach(step => {
            setTimeout(step.bind(self), 100);
        });
    }
};

bannerAnimation.doSteps();
Jamiec
  • 133,658
  • 13
  • 134
  • 193