Skip to content Skip to sidebar Skip to footer

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 = []

Solution 1:

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();

Solution 2:

Depending on where you call the function from you can do it like this: Using call to set the context of this inside your function.

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

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

var m = new MealPlan();

console.log(m.protein.getTotalSets.call(m));

Solution 3:

There are several different ways you could go about this...here's a way that may have been closest to your original intent:

function MealPlan() {
    var self = this;
    self.sets = [];

    self.protein = {
        getTotalSets: function() { return self.sets.length; },
        anotherMethod: function() { /* ... */ },
    }
}

var mp = new MealPlan();
mp.protein.getTotalSets();

You could alternatively implement protein as a trait; take a look at http://soft.vub.ac.be/~tvcutsem/traitsjs/.


Post a Comment for "Nested Object Literal Access Parent"