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

Sign up to request clarification or add additional context in comments.

1 Comment

@nickzoum but this.property = ... wouldn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.