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

时间:2018-06-16 22:02:32

标签: javascript

我有对象列表。每个对象都有一些方法和属性,比如

  

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 个答案:

答案 0 :(得分:3)

不确定

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

const obj0 = {
  add: (a, b) => a + b
}

const arr = [];

arr[0] = obj0;

console.log(arr[0].add(1,2));

答案 1 :(得分:1)

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作为构造函数实例化对象。按要求。