Search code examples
javascriptobject-literal

Nested Object Literal Access Parent


I'm trying to access a parent within an object literal graph and I am not sure the correct way to accomplish this. Here is some pseudo code.

function MealPlan() {
  this.sets = []
}

MealPlan.prototype = {
  protein: {
    getTotalSets: function() {
      return this.sets.length;
    }
  }
};

I am trying to get a hold of the sets property from within the getTotalSets function.


Solution

  • This actually can't be done (without hacking using call or apply the way @RichardMacarthy showed) because you are creating a new context by creating a new object context (e.g. protein) on the prototype. The prototype is used to add methods to an object, not properties.

    Alternatively, you could turn your property in a method which would allow you to retain the original context of the object.

    function MealPlan() {
      this.sets = []
    }
    
    MealPlan.prototype = {
      protein: function() { 
         var self = this; 
         return { 
            getTotalSets: function() { return self.sets.length; },
            anotherMethod: function() { /* ... */ },
         }
       }
    };
    
    var mp = new MealPlan();
    mp.protein().getTotalSets();