在新对象参数中使用“this”选择器

Using 'this' selector in new object parameters

本文关键字:this 选择器 参数 新对象 对象      更新时间:2023-09-26

我正在开发一个javascript pong模拟器,我想让它尽可能面向对象。您可以在此处查看代码:

Github存储库

显示球拍如何不呈现的代码笔

您可以看到我注释掉的用于桨大小的变量。我将大小移到了 Paddle 和 Player 对象构造函数上,以使其更加面向对象。

我有一个 Paddle 对象构造函数:

function Paddle(x, y) {
    this.x = x;
    this.y = y;
    this.width = width/8;
    this.height = this.width/5;
    this.center = width/2 - this.width/2;
    this.x_speed = 0;
    this.y_speed = 0;
};

和一个 Player 对象构造函数:

function Player() {
    this.startX = Paddle.center;
    this.startY = height - Paddle.height;
    this.paddle = new Paddle(this.startX, this.startY);
    this.score = 0;
};

我也有类似的计算机播放器构造函数。

在脚本结束时,我创建对象并开始游戏:

var player = new Player();
var computer = new Computer();
var ball = new Ball(ballStartPositionX,ballStartPositionY);

我的桨没有被创建,我认为这是由于我如何使用this.startX = Paddle.center;this.paddle = new Paddle(this.startX, this.startY);,特别是我如何在新的桨参数中使用"this"选择器。有什么想法吗?

您在哪里:

function Player() {
    this.startX = Paddle.center;
    this.startY = height - Paddle.height;
    this.paddle = new Paddle(this.startX, this.startY);
    this.score = 0;
};

您正在尝试读取 Paddle 构造函数的中心属性,但这是 Paddle 实例的属性。您需要将初始 xy 坐标传递给播放器构造函数,因此:

function Player(x, y) {
    // create paddle instance first
    this.paddle = new Paddle(x, y);
    // Use the paddle instance, not the constructor
    this.startX = this.paddle.center;
    this.startY = height - this.paddle.height; // height is a global
    this.score = 0;
};

当您创建播放器实例时,您必须说出它们的位置:

var player = new Player(xCoord, yCoord);

因此,它可以在构造 Paddle 实例时使用坐标。