gpt4 book ai didi

javascript - 使用对象数组访问类函数

转载 作者:行者123 更新时间:2023-11-30 20:35:38 25 4
gpt4 key购买 nike

我在用 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);
}
}

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 不是函数”

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 数组,你可以 .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

关于javascript - 使用对象数组访问类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49869694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com