您可以使用函数创建Objects,使用new operator
这不是创建对象的唯一方法,有很多方法,但它是与您的代码最匹配的方法。
Objects 是 JavaScript 的基本构建块(就像 Java 的类),在开始使用它们之前需要深入了解它们
基本示例
// It is customary for object instantiated via new to have capitalized names
function Block(x, y, w, h, color) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.color = color;
}
var b1 = new Block(500, 350, 100, 100, 'gray');
drawBlock(b1);
function drawBlock(block) {
ctx.fillStyle = block.color;
ctx.fillRect(block.x, block.y, block.w, block.h);
}
function update() {
if((pX >= b1.x - pW) && (pY >= b1.y - pH)) {
pX = b1.x - pW;
}
}
或
// It is customary for object instantiated via new to have capitalized names
function Block(x, y, w, h, color) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.color = color;
}
Block.prototype = {
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.w, this.h);
},
};
var b1 = new Block(500, 350, 100, 100, 'gray');
b1.draw();
或
const Block = (x, y, w, h) => ({x, y, w, h});// this method does not require new operator
var b1 = Block(500, 350, 100, 100, 'gray');
drawBlock(b1);
function drawBlock(block) {
ctx.fillStyle = block.color;
ctx.fillRect(block.x, block.y, block.w, block.h);
}
或
const blockCommon = {
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.w, this.h);
},
};
const Block = (x, y, w, h) => ({x, y, w, h, ...blockCommon});
var b1 = Block(500, 350, 100, 100, 'gray');
b1.draw();
或十几种或更多创建对象的方法。