0

I'm working with ReactJS, but I think my question might be a general javascript question. I have two classes Url and QueryVars. I want Url to be able to call all the methods of QueryVars, as if I extended Url from QueryVars. So I did something like this:

export default class Url {

  constructor()
  {
    this.queryVars = new QueryVars();

    console.log(this.queryVars);
    for(let x in this.queryVars)
    {
      console.log(x); // this never gets fired
      if(typeof this.queryVars[x] == "function")
      {
        this[x] = this.queryVars[x].bind(this.queryVars);
      }
    }
  }
}

default class QueryVars {

  init()
  {
    /* do something */
  }
  getQS(key)
  {
    /* do something */
  }
  getPage(key)
  {
    /* do something */
  }
}

The thing is that the console.log(x) does not get fired. I'm unable to retrieve the methods of this.queryVars. What am I doing wrong here?

Eventually, I want to assign a few more objects into the Url.constructor and bind more methods of those objects, so that it seems like I'm implementing multiple inheritance, or composing a new class out of other classes. So that I can:

do url.getQS() instead of url.queryVars.getQS()
do url.getIP() instead of url.ip.getIP()
etc...

My code above was based on what I learned in this question here: Is there a way to print all methods of an object in javascript?

John
  • 32,403
  • 80
  • 251
  • 422
  • 1
    i think you want a mixin? http://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/ – enno.void Aug 15 '18 at 17:36
  • @mr.void Ooohhh yeah, that's what I'm trying to achieve. Ok, will need some time to read that article, because it doesn't sound like it's as easy to achieve as what I posted in my question. – John Aug 15 '18 at 17:43
  • in a simple cause you could just do this: Object.assign(obj1, obj2); – enno.void Aug 15 '18 at 17:52
  • I'm not sure of a good pattern, but the reason your code isn't working is because: 1. class methods are not defined on the object, but on the class prototype and 2. methods are not enumerable, so they don't show up in `for…in`. You could have to do something like `for(let x of Object.getOwnPropertyNames(Object.getPrototypeOf(this.queryVars)))` to enumerate them. – Mark Aug 15 '18 at 17:55

0 Answers0