写JS对象中的奇怪部分

时间:2017-08-19 10:08:15

标签: javascript

我是javascript的新手。我在codepen.io上玩,学习一些javascript项目。我找到了Pong-JS实现。我找到了一些我无法弄明白的东西。因为我不知道它是什么样的东西

var Game = {
initialize: function () {
    this.canvas = document.querySelector('canvas');
    this.context = this.canvas.getContext('2d');

    this.canvas.width = 1400;
    this.canvas.height = 1000;

    this.canvas.style.width = (this.canvas.width / 2) + 'px';
    this.canvas.style.height = (this.canvas.height / 2) + 'px';

    this.player = Paddle.new.call(this, 'left');
    this.paddle = Paddle.new.call(this, 'right');
    this.ball = Ball.new.call(this);

    this.paddle.speed = 8;
    this.running = this.over = false;
    this.turn = this.paddle;
    this.timer = this.round = 0;
    this.color = '#2c3e50';

    Pong.menu();
    Pong.listen();
}, //there are another properties

我的问题为什么它使用this.来制作一些变量。为什么不使用var?因为我发现了this.语法,我无法将这些解释联系起来。 我希望你能帮我理解这行代码。

这是codepen:https://codepen.io/gdube/pen/JybxxZ?editors=1010

1 个答案:

答案 0 :(得分:-1)

这指的是当前的背景。在这种情况下,上下文是Game对象。所以当你这样做时:

Game.initialize();

这个指的是游戏,所以一切都存储在游戏中,例如:

Game.canvas

这特别有用,因为你的数据是正确的,因此我们不知道它所属的变量 canvas ,我们知道 Game.canvas 游戏有关。另一个很酷的事情是你可以轻松创建新游戏:

var pong = Object.create( Game );
pong.initialize();
console.log( pong.canvas );