我如何在 JavaScript 中的构造函数中初始化对象数组
How do i initialise an array of object in constructor in JavaScript
我想创建一个 class,其中包含一个对象数组
构造函数。这个想法是在 canvas 中创建矩形
使用对象内部的值。
我有这个数组:
const blueBoxs = [
{ x: 38, y: 31, w: 50, h: 50 },
{ x: 47, y: 31, w: 25, h: 19 },
]
我尝试了以下方法:
class Collision {
constructor (boxs) {
this.boxs=boxs;
};
createBox(boxs=[]){
for (let box of boxs) {
ctx.fillStyle = 'blue'
ctx.fillRect(box.x, box.y, box.w, box.h)
}
return
};
};
let createBluebox= new Collision(blueBoxs);
createBluebox.createBox();
感谢您的帮助。
如前所述,添加 this
有效。请参阅 this.boxs
的示例
const blueBoxs = [
{
x: 38,
y: 31,
w:50,
h:50,
},
{
x: 47,
y: 31,
w:25,
h:19,
} ]
class Collision {
constructor (boxs) {
this.boxs=boxs;
};
createBox(boxs=[]){
for (let box of this.boxs) {
ctx.fillStyle = 'blue'
ctx.fillRect(box.x, box.y, box.w, box.h)
}
return
};
};
let canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
let createBluebox= new Collision(blueBoxs);
createBluebox.createBox();
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
我到处都忘记了 this
关键字。谢谢大家!
class Collision {
constructor (boxs, ctx) {
this.boxs=boxs;
this.ctx=ctx;
};
createBox(){
for (let box of this.boxs) {
this.ctx.fillStyle = 'blue'
this.ctx.fillRect(box.x, box.y, box.w, box.h)
}
return
};
};
let createBluebox= new Collision(blueBoxs, ctx);
createBluebox.createBox();
我想创建一个 class,其中包含一个对象数组 构造函数。这个想法是在 canvas 中创建矩形 使用对象内部的值。
我有这个数组:
const blueBoxs = [
{ x: 38, y: 31, w: 50, h: 50 },
{ x: 47, y: 31, w: 25, h: 19 },
]
我尝试了以下方法:
class Collision {
constructor (boxs) {
this.boxs=boxs;
};
createBox(boxs=[]){
for (let box of boxs) {
ctx.fillStyle = 'blue'
ctx.fillRect(box.x, box.y, box.w, box.h)
}
return
};
};
let createBluebox= new Collision(blueBoxs);
createBluebox.createBox();
感谢您的帮助。
如前所述,添加 this
有效。请参阅 this.boxs
const blueBoxs = [
{
x: 38,
y: 31,
w:50,
h:50,
},
{
x: 47,
y: 31,
w:25,
h:19,
} ]
class Collision {
constructor (boxs) {
this.boxs=boxs;
};
createBox(boxs=[]){
for (let box of this.boxs) {
ctx.fillStyle = 'blue'
ctx.fillRect(box.x, box.y, box.w, box.h)
}
return
};
};
let canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
let createBluebox= new Collision(blueBoxs);
createBluebox.createBox();
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
我到处都忘记了 this
关键字。谢谢大家!
class Collision {
constructor (boxs, ctx) {
this.boxs=boxs;
this.ctx=ctx;
};
createBox(){
for (let box of this.boxs) {
this.ctx.fillStyle = 'blue'
this.ctx.fillRect(box.x, box.y, box.w, box.h)
}
return
};
};
let createBluebox= new Collision(blueBoxs, ctx);
createBluebox.createBox();