Accessing main class attributes from sub-class callback in javascript

Javascript code I want to use this.progressbar inside a media callback function

  class CatMusicPlayer {

  constructor(url,playPauseBtn,progressbar,progressTime,durationTime) {
    this.url = url;
    this.playPauseBtn = playPauseBtn;
    this.progressbar = progressbar;
    this.progressTime = progressTime;
    this.durationTime = durationTime;

    new Media(url,null,this.logerror,function(mediaStatus){

        /*
            i want to use this.progressbar,
            but in this block "this" reffers to Media class.
            Media is kind of another class similar to CatMusicPlayer
        */

    });
  }

      

+3


source to share


2 answers


cache value this

for another variable for example const _thisMP = this;

 and use it later_thisMP.progressbar();

or in your case, you can even call directly progressbar()

as it is available



class CatMusicPlayer {

  constructor(url,playPauseBtn,progressbar,progressTime,durationTime) {
    this.url = url;
    this.playPauseBtn = playPauseBtn;
    this.progressbar = progressbar;
    this.progressTime = progressTime;
    this.durationTime = durationTime;
    const _thisMP = this;

    new Media(url,null,this.logerror,function(mediaStatus){
       _thisMP.progressbar(); // call here

        /*
            i want to use this.progressbar,
            but in this block "this" reffers to Media class.
            Media is kind of another class similar to CatMusicPlayer
        */

    });
  }

      

+2


source


class CatMusicPlayer {

  constructor(url,playPauseBtn,progressbar,progressTime,durationTime) {
    this.url = url;
    this.playPauseBtn = playPauseBtn;
    this.progressbar = progressbar;
    this.progressTime = progressTime;
    this.durationTime = durationTime;
    let self = this;
    new Media(url,null,this.logerror,function(mediaStatus){
       self.progressbar();


    });
  }

      



0


source







All Articles