-1

I am currently learning about JavaScript object oriented programming and seem to have run into a problem I couldn't figure out by googling so I am gonna try stack-overflow though I rarely ask questions on forums.

Anyway, I ran into an error while playing with functions after trying to convert some old non OOP code into OOP code. Note there are probably more errors than just the one I am asking about so don't trust any of the code below. The error I am getting is an Uncaught TypeError: Cannot read property fadeInAnimations of undefined.

Also, all advice to improve this code is really appreciated.

let mainSection = {
    msTime : 0,

    fadeInAnimation : ((element, delayTime) => {
        $(element).delay(delayTime).fadeIn(1000)
    }),

    mainPageElements : [`.traninigTimes`, `.registration`, `.trainingFee`].forEach((element) => {
        this.fadeInAnimation.fadeInAnimations(element, this.msTime)
        this.msTime += 1000;
    })
};
5
  • You have function called fadeInAnimation, and are calling fadeInAnimations? But the error is telling you that if you are calling x.fadeInAnimations then x is undefined Commented Feb 4, 2019 at 15:40
  • Put simply, this.fadeInAnimation is undefined. Could you please provide a minimal reproducible example demonstrating the exact problem. Commented Feb 4, 2019 at 15:40
  • fadeInAnimation is a function, yet you're trying to use it as an object with a fadeInAnimations property? Commented Feb 4, 2019 at 15:40
  • shouldn't it be this.fadeInAnimations(element, this.msTime) ? Commented Feb 4, 2019 at 15:41
  • You don’t have a function object instance here, you only have a normal object you created yourself using object notation. Therefor, this likely points to the global window object - and that doesn’t have a method called fadeInAnimations. If you need to access the method from outside the context of this object, then that would be mainSection.fadeInAnimations Commented Feb 4, 2019 at 15:43

1 Answer 1

2

The this context is different in the forEach callback. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

In the callback this refers to the callback context.

let mainSection = {
    msTime : 0,

    fadeInAnimation : ((element, delayTime) => {
        $(element).delay(delayTime).fadeIn(1000)
    }),

    mainPageElements : [`.traninigTimes`, `.registration`, `.trainingFee`].forEach(((element) => {
        this.fadeInAnimation.fadeInAnimations(element, this.msTime)
        this.msTime += 1000;
    }).bind(this))
};
Sign up to request clarification or add additional context in comments.

Comments

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.