使用对象数组

时间:2018-04-17 04:00:14

标签: javascript class oop p5.js

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

我有一个名为" Boxes"的班级。我已经在使用" 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);
    }
}
  

对于标准变量,它的效果非常好。

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

当我尝试不同的东西时,它不起作用。以下示例。

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不是一个功能"

  

虽然我用括号写了show()函数。它说   " myboxes [1] .show不是一个功能"我用的时候工作正常   box1.show()。如何使用对象数组访问函数?   我要尝试别的吗?你有什么建议吗?

2 个答案:

答案 0 :(得分:1)

如果你想拥有一个 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

答案 1 :(得分:0)

如果您创建非Boxes对象,则其原型链中的任何位置都没有show。但是没关系,如果您有权访问该类,则可以使用非Boxes对象调用prototype方法作为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能够正常工作。< / p>