JavaScript 构造函数参数

标签 javascript html oop constructor

我一直在关注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/

相关文章:

java - 使用 0 到另一个 java 类中的多个对象初始化对象

java - 常量类的接口(interface)模式

javascript - JQuery UI 拖放(获取 Draggable 值以显示和隐藏文本区域框)

php - 可以将 PHP 集成到 Javascript 中吗?

javascript - Jquery中达到数值后如何重置递增变量

html - 响应时将图像保留在框内

html - 移动 View 上水平滚动画廊的问题

php - 从 php html 中的 sql 结果填充下拉列表中获取选定的值

javascript - ionic 框架类型错误: Cannot read property 'udp' of undefined

javascript - Object.create 使用构造函数创建对象