Home > Back-end >  Execute JavaScript function defined inside a class constructor, using the class's object
Execute JavaScript function defined inside a class constructor, using the class's object

Time:01-08

I've created a class "BFSPlayer" in Javascript with a constructor, and inside this constructor I've defined a function(which is not executed) named "myFunction". Then I've created an object "obj" of BFSPlayer class and then I want to run that myFunction for this object. Here's how I'm trying to do it, but it's not working:

class BFSPlayer {
  constructor(args){
    var player;
    function myFunction(){
        player = {
            videoId: args
        }
    }
  }
}

var obj=new BFSPlayer('video-id');
obj.constructor.myFunction();

Any help would be thankful to me

CodePudding user response:

Example:

class BFSPlayer {
  player = {};

  constructor(args){
    this.player = {
      videoId: args,
    };
    
  }
  
  // I cant imageing what you wanna do here)
  //function myFunction(){
  //      player = {
  //          videoId: args
  //      }
  //  }
}

var obj = new BFSPlayer('video-id');

console.log(obj); //{ "player": { "videoId": "video-id" } }

// if you extract function from comment in class, you can use in this way
//obj.myFunction();

  • Related