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!

1

1 Answer 1

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();

1
  • @nickzoum but this.property = ... wouldn't.
    – Jamiec
    Commented Jan 21, 2020 at 11:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.