gpt4 book ai didi

JavaScript 构造函数参数

转载 作者:行者123 更新时间:2023-12-02 19:41:19 27 4
gpt4 key购买 nike

我一直在关注this tutorial关于如何在 HTML5 中制作一个简单的游戏,我遇到了一个我无法理解的参数的有趣用法...这里作者创建了一个名为 Bullet 的构造函数,带有单个参数 I,但看看他如何使用 I。什么是这是怎么回事?我不明白:

function Bullet(I) {
I.active = true;

I.xVelocity = 0;
I.yVelocity = -I.speed;
I.width = 3;
I.height = 3;
I.color = "#000";

I.inBounds = function() {
return I.x >= 0 && I.x <= CANVAS_WIDTH &&
I.y >= 0 && I.y <= CANVAS_HEIGHT;
};

I.draw = function() {
canvas.fillStyle = this.color;
canvas.fillRect(this.x, this.y, this.width, this.height);
};

I.update = function() {
I.x += I.xVelocity;
I.y += I.yVelocity;
};

return I;
}

最佳答案

根据该教程,Bullet 不是构造函数,只是一个接受现有对象、增强(追加)属性并返回对象的函数。然后,它将返回的对象(带有附加属性)放入 playerBullets 数组中。

playerBullets.push(Bullet({  //the Bullet call, passing an object
speed: 5,
x: bulletPosition.x,
y: bulletPosition.y
}))

Bullet 返回的对象将如下所示:

{
//the passed object
x:...,
y:...,
speed:...,
//the added properties
xVelocity:...,
yVelocity:...,
...,
update:function(){...}
}

关于JavaScript 构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10368645/

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