0

I have following code:

var ObjectOne = {
    a : {
        b : 4,
        ...
    }        
    observer : 0,
    ...

    init() { 
        this.a.b = 5;           
        ...
        this.observer = new IntersectionObserver(this.onIntersection, ...);               
        this.observer.observe(...);
        ...       
    }
    onIntersection(entries, observer) {
        ...
        var test = this.a.b;
        ...
    }
}

And when run it, i have an error at a moment, when onIntersection() is executed. The error is: Uncaught TypeError: Cannot read property 'b' of undefined. How i can pass 'this' instance of ObjectOne to onIntersection() function?

Alex Shul
  • 500
  • 7
  • 22
  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Heretic Monkey Nov 27 '18 at 18:21

1 Answers1

0

Thanks to Heretic Monkey for useful link How to access the correct this inside a callback? - it was helpful and give me a direction for search. And more helpful information was at Use of the JavaScript 'bind' method. Adding bind() function solve the problem:

var ObjectOne = {
    a : {
        b : 4,
        ...
    }        
    observer : 0,
    ...

    init() { 
        this.a.b = 5;           
        ...
        this.observer = new IntersectionObserver(this.onIntersection.bind(this), ...);               
        this.observer.observe(...);
        ...       
    }
    onIntersection(entries, observer) {
        ...
        var test = this.a.b;
        ...
    }
}
Alex Shul
  • 500
  • 7
  • 22