Nested Object Literal Access Parent

核能气质少年 提交于 2019-11-27 19:38:31

问题


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.


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



回答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));



回答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/.



来源:https://stackoverflow.com/questions/29491267/nested-object-literal-access-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!