1

I am trying to order my functions in my Class like that:

- Client Class
  - GAME1
    - searchPlayer
    - getStats
  - GAME2
    - getStats
    - someotherfunction

So that when I use new Client({}).GAME1.searchPlayer() I can access this function.

class Client {

constructor(options = {}) {
    this.options = options;

    if (!this.options.apiKey) return new Error('Missing API-Key');
}

GAME1 = {
    searchPlayer (searchQuery='') {
        return this.request(...);
    }
};

GAME2 = {...}

request(uri) {
    return new Promise((resolve, reject) => {
        }
}

module.exports = Client;

But like that I can not access this.request

  • [Don't do that](https://stackoverflow.com/questions/15884096/organize-prototype-javascript-while-perserving-object-reference-and-inheritance). [It won't work](https://stackoverflow.com/questions/16502467/prototype-deep-scope-of-this-to-access-instances-scope). – Bergi Dec 18 '20 at 22:15
  • How else should I do it? –  Dec 19 '20 at 08:06
  • Put the methods directly on the class. Give them a prefix if absolutely necessary. But (from the little you've shown) it seems like these methods [don't actually belong in the same class](https://en.wikipedia.org/wiki/Single-responsibility_principle) at all. Instead, write two classes - `Game1Client` and `Game2Client` - that will have different methods and different implementations. – Bergi Dec 19 '20 at 12:22

1 Answers1

0

To access request using this you can make a simple change as follows:

class Client {

constructor(options = {}) {
    this.options = options;

    
}

GAME1 = {
    searchPlayer: (searchQuery='') => {
        return this.request('uri');
    }
};

GAME2 = {}

request(uri) {
    console.log(uri);
    return new Promise((resolve, reject) => {
    
        })
}
}
const client = new Client ();
console.log(client.GAME1.searchPlayer())

Question might by why so for that you need to understand javascript scope

(this keyword belongs to which object ?)

I have defined two internalVar one belongs to scope class and another belongs to prop

example 1

class scope {
constructor (){
  this.internalVar = 2;
  
}
  prop = {
  internalVar:1,
    func () {
    console.log(this.internalVar);
    }
   
  }
  
}

const obj =  new scope();
obj.prop.func()
// expected output: 1

example 2

class scope {
constructor (){
  this.internalVar = 2;
  
}
  prop = {
  internalVar:1,
  func: () => {
    console.log(this.internalVar);
    }
   
  }
  
}

const obj =  new scope();
obj.prop.func()
// expected output: 2