dimanche 16 septembre 2018

Javascript: Getting the parent object, in OOP composite pattern

My program implements the composite pattern, that looks more or less like that:

class Selector{
   constructor(){
       this.selectors=[]
   }

   addSelector(selector){
    this.selectors.push(selector);
  }

   processSelector(){
       this.selectors.forEach(selector=>selector.processSelector())
   }
}

What i'd like to know, is whether there's some way of giving the child object a reference to the parent one, without just passing the "this" in the addSelector() method. What i don't want, would look something like this:

addSelector(selector){
    selector.parent = this;
    this.selectors.push(selector);
}

I find this to be a bit "ugly". How would i just get the selectors array, in which the object is referenced(and then of course the object in which it sits)? In more general words: How to get the the array of an element?

Aucun commentaire:

Enregistrer un commentaire