使用对象数组访问 class 函数

Accessing a class function with array of objects

我在 p5.js 中编码,我注意到一个我无法通过的问题。

我有一个名为 "Boxes" 的 class。我已经在使用 "Boxes" 拥有的功能。但是当我尝试使用应用于对象数组的函数时,它没有用。我该如何解决这个问题?

class Boxes
{
    constructor()
    {
        this.x;
        this.y;
        this.r=222;
        this.g=55;
        this.b=111;
    }

    show()
    {
        fill(this.r,this.g,this.b);
        rect(this.x,this.y,50,50);
    }
}

For standard variable it works perfectly like this.

var box1 = new Boxes();
box1.show(); // It works.

When I tried something different it doesn't work. The example below.

var myboxes = [{'x':this.x, 'y':this.y}]; // That's OK :)

myboxes.push({x:100, y:100}); // That's OK too :)

myboxes[1].show(); // But. It gives an error :/

它说:"myboxes[1].show is not a function"

Although I write the show() function, with parentheses. It says "myboxes[1].show is not a function" It works fine when I use box1.show(). How can I access the functions using an array of objects? Shall I try something else? What are you suggesting?

如果您创建一个非 Boxes 对象,它的原型链中的任何地方都没有 show。但没关系,如果您有权访问 class,您可以使用非 Boxes 对象调用原型方法作为 this:

class Boxes {
  show() {
    console.log(this.x);
  }
}

var myboxes = [{'x':this.x, 'y':this.y}];
myboxes.push({x:100, y:100});
Boxes.prototype.show.call(myboxes[1]);

但请注意,您还需要在非 Boxes 对象上放置 rgb 属性,以便 show 正常工作.

如果你想要一个 Boxes 的数组,你可以 .push() 像这样的新对象:

class Boxes {
  constructor(param) {
    this.x = param.x;                     //Assign the x   
    this.y = param.y;                     //Assign the y
    this.r = 222;
    this.g = 55;
    this.b = 111;
  }

  show() {
    console.log(this.x, this.y);          //Test code,

    //fill(this.r,this.g,this.b);
    //rect(this.x,this.y,50,50);
  }
}

var myboxes = [];
myboxes.push(new Boxes({x: 3,y: 20}));     //Create a new box and push to the array
myboxes.push(new Boxes({x: 30,y: 200}));   //Create anothe one and push to the array

myboxes[1].show();                         //<-- You can show the x and y of element 1