Javascript 动态更改受类函数影响的类变量

Javascript 动态更改受类函数影响的类变量,javascript,class,object,Javascript,Class,Object,考虑一个包含一组其他对象的类 function Food= (){ this.apples = 8; this.orange = 6; this.peach = 3; } 现在,我可以创建一个add函数 Food.prototype.add(food){ this.apple += food.apple; this.orange+=food.orange; this.peach+=food.peach; } 但是,如果我想动态地向食物中添加另一种东西,那么food.prototy

考虑一个包含一组其他对象的类

function Food= (){
 this.apples = 8;
 this.orange = 6;
 this.peach = 3;
}
现在,我可以创建一个add函数

Food.prototype.add(food){
 this.apple += food.apple;
 this.orange+=food.orange;
 this.peach+=food.peach;
}
但是,如果我想动态地向食物中添加另一种东西,那么food.prototype.add还会添加哪种食物呢

第一个问题是,是否有一种简单的方法来添加类中的所有对象

第二个问题是:我本可以按如下方式编写代码

function Food = (){
this.apples = 8;
this.orange = 6;
this.peach = 3;
this.addArray = [];
this.addArray.push(this.apples);
this.addArray.push(this.orange);
this.addArray.push(this.peach);
} 

Food.prototype.add(food){
 for (i=0, i<this.addArray.length, i++){
  this.addArray[i]+=food.addArray[i];
 }
}
功能食品=(){
这个苹果=8;
这个橙色=6;
这个桃子=3;
this.addArray=[];
this.addArray.push(this.apples);
this.addArray.push(this.orange);
this.addArray.push(this.peach);
} 
食物。原型。添加(食物){

对于(i=0,i嘿,你也可以试试这个

Food.prototype.add(food){
 for(var i in food)
 {
    if(this[i] != undefined)
    {
       this[i] += food[i];
    }
 }
}

我想你要找的是

function Food() {
    this.apples = 8;
    this.orange = 6;
    this.peach = 3;
    this.addArray = ["apples", "orange", "peach"];
} 

Food.prototype.add = function(food) {
    for (var i=0, i<this.addArray.length, i++) {
        this[this.addArray[i]] += food[this.addArray[i]];
    }
};
功能食品(){
这个苹果=8;
这个橙色=6;
这个桃子=3;
this.addArray=[“苹果”、“橘子”、“桃子”];
} 
Food.prototype.add=功能(食品){

对于(var i=0,依我看,您似乎在将两种不同的结构合并在一起。您的
食物
实际上是
食物
包含名称和数量对。您的思路是正确的,尽管您使用对象而不是数组的想法似乎是一种更好的方法,我的意思是唯一有意义的。)您可以使用
for(obj中的var item){…}
遍历对象属性,尽管根据您尝试执行的操作,最好使用类似数组的数据结构。主要原因是,如果您想向食物添加任何其他属性,则可能不是您想要“添加”的数字。谢谢您的回答。我有一个后续问题。如果我想使用映射,我会将this.addArray更改为this.addMap=new map(),然后将this.addMap.set(“apples”,this.apples)等等。是吗?不,我的意思是你根本就不会有一个
.apples
属性。一个
食物
对象只会包含一个
this.fruits=新地图([[“apples”,8],“orange”,6],“peach”,3]);
添加
方法会合并两个地图。