代码之家  ›  专栏  ›  技术社区  ›  Josef

在对象列表中访问对象的方法

  •  -3
  • Josef  · 技术社区  · 6 年前

    我有物品清单。每个对象都有一些方法和属性,如

    myobject.setvalue(20);

    我需要创建3个、5个或更多对象并将它们存储在列表中。我就是这么做的:

     var listOfObj = [];
     for (var x = 0; x<3; x++)
     {
        listOfObj[x] = new myObject({ id: "obj" + x + ""});
     }
    

    所以,我创建了3个元素的数组,每个元素都是对象。

    现在我想访问对象的方法和/或属性,例如:

    obj1.Refresh();
    

    怎么做?有可能吗? `

    2 回复  |  直到 6 年前
        1
  •  3
  •   Matt Morgan    6 年前

    当然。

    只需通过数组索引访问对象,然后调用以下函数:

    const obj0 = {
      add: (a, b) => a + b
    }
    
    const arr = [];
    
    arr[0] = obj0;
    
    console.log(arr[0].add(1,2));
        2
  •  1
  •   Attersson    6 年前

    ES 5:

        function myObject(v){
            this.id= "obj " + v;
            this.value = 0;
            this.that = this;
            this.SetValue = function(val){ //functions need context.
                this.value = val; // use "that" as this
            }
            this.getValue = ()=>this.value; // lambda functions inherit context
        
            this.Refresh = function(args){
                //do stuff
                console.log("Refreshed!");
            }
        }
        
         var listOfObj = [];
         for (var x = 0; x<3; x++)
         {
            listOfObj.push(new myObject(x));
            listOfObj[x].SetValue(x);
            console.log(listOfObj[x].getValue());
         }

    ES 6:

    不支持代码段

    class myObject {
      constructor(v){
        this.id= "obj " + v;
        this.value = 0;
        this.that = this;
      }      
      this.SetValue = (val)=> {that.value = val;};
      this.getValue = ()=>this.value;
    
      this.Refresh = function(args){
        //do stuff. use "that" as this
        console.log("Refreshed!");
      }
    }
    
    var listOfObj = [];
    for (var x = 0; x<3; x++)
    {
      listOfObj.push(new myObject(x));
      listOfObj[x].SetValue(x);
      console.log(listOfObj[x].getValue());
    }
    

    这将使用myobject作为构造函数实例化对象。按要求。