0
export class PageScroll {


    constructor (args)
    {

         this.$scrollableElements = [];
         this.$scrollClassName = args;
         
         this.Init();
    }
    
    
    
    Init ()
    {      // Correctly calls detectScrollableElements
       document.addEventListener('wheel', this.detectScrollableElements, 'true');
     
       // correctly prints variable
       console.log('page = ' + this.scrollClassName);   
    }
    
    
    
    


   
   
   detectScrollableElements()
   {
       console.log("name1 = " + this.$scrollClassName);  // this context lost, $scrollClassName 'undefined'!!!
       
       let $scrollEle = document.getElementsByClassName(this.$scrollClassName);
       
           for(let items in $scrollEle)
           {
               this.$scrollableElements[$scrollEle[items].id] = document.getElementById($scrollEle[items].id).getBoundingClientRect();
            
                console.log(`${items} is at ${$scrollEle[items]} \n`);
           }
       console.log("name = " + this.$scrollClassName);
   }







}


window.onload = () => {
   const $page = new PageScroll('page_scroll');
}

It's seems I'm losing the context of 'this' when I call a method from within a method. I have tried using bind(), call(), as well as an arrow function. Why does 'this' not stay bound to the Class?

Thanks for any help on this confusion.

  • How exactly did you use `.bind()`? You have to do that; functions do not have any intrinsic permanent relationship with any particular object unless you create a function with `.bind()` or use an `=>` function. – Pointy Oct 04 '20 at 19:23
  • I was using it incorrectly! I was attempting to bind the Init.bind(this). The problem was not losing the "this" context within the class but it was the event handler that was losing the context of "this". You have to bind "this" within the function of addEventListener like so: document.addEventListener('wheel', this.detectScrollableElements.bind(this), 'true'); – lulzicon Oct 06 '20 at 01:34

0 Answers0