在新对象参数中使用“this”选择器
Using 'this' selector in new object parameters
我正在开发一个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 实例的属性。您需要将初始 x 和 y 坐标传递给播放器构造函数,因此:
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 实例时使用坐标。
相关文章:
- 使用THIS比使用选择器更有效吗
- 将jQuery选择器与“this”相结合
- 正在获取$this的选择器
- 在Jquery中将$(this)与css类选择器一起使用
- Jquery $this属性选择器是否包含单词
- 在新对象参数中使用“this”选择器
- 如何使用“this”作为选择器的一部分
- 如何在 jQuery 中使用“this”的子元素作为选择器
- jQuery $(this) 伪选择器
- 如何在 JQuery 中使用带有“this”的相邻同级选择器
- jQuery两个不同的选择器,但根据哪一个定义$(this)
- 在类选择器中传递 jQuery this.id
- 当有多个选择器时处理 $(this)
- 在 Jquery 中使用选择器而不是“this”
- javascript “this” 如何处理来自 jquery 的多个选择器返回
- 可以使用$(this)和通用选择器(*)
- 比较$this选择器和JQuery
- 如果this()选择器在函数中使用,它将引用哪个选择器(jQuery)
- 如何使$(this)选择器专注于当前元素?
- jQuery插件参数中的$(this)选择器指针