skip to Main Content

I need to call a member function from the callback function in an event listener which is also in another member function. Here is a simplified example:

class C {

  finished() {
    console.log ('over');
  }
  
  timer() {
    console.log('started')
    setTimeout(function fct() {
        this.finished();
    },500);
  }
}


let c = new C();

c.timer();

I get the following result : Uncaught TypeError: this.finished is not a function". I understand that the callback function is no longer member of the class C.

Is there a way to call the finished() member function from the callback function?

Here is a JSFiddle

2

Answers


  1. You need to bind this

    class C {
        finished() {
            console.log('over');
        }
    
        timer() {
            console.log('started');
            setTimeout(function fct() {
                this.finished();
            }.bind(this), 500);
        }
    }
    
    let c = new C();
    c.timer();

    or just hand over the function

    this.finished
    

    which keeps the reference of this.

    class C {
        finished() {
            console.log('over');
        }
    
        timer() {
            console.log('started');
            setTimeout(this.finished, 500);
        }
    }
    
    let c = new C();
    c.timer();
    Login or Signup to reply.
  2. this inside the setTimeout callback will refer to window object not the C object, So you need to bind the setTimeout callback with the C object

    class C {
    
      finished() {
        console.log ('over');
      }
      
      timer() {
        console.log('started')
        setTimeout(function fct() {
            // ... some code.
            this.finished();
        }.bind(this),500);
      }
    }
    
    
    let c = new C();
    
    c.timer();

    Or you can use the arrow function which will make this will refer to the this of the outer scope.

    class C {
    
      finished() {
        console.log ('over');
      }
      
      timer() {
        console.log('started')
        setTimeout(() => {
            this.finished();
        },500);
      }
    }
    
    
    let c = new C();
    
    c.timer();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search