Write JS对象中的奇怪部分
Weird Part in Write JS object
我是 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.
语法,所以我无法将这些解释联系起来。
我希望你能帮助我理解这行代码。
this指的是当前上下文。在这种情况下,上下文是 Game 对象。所以当你这样做时:
Game.initialize();
this 指的是 Game,因此所有内容都存储在 Game 中,例如:
Game.canvas
这特别有用,因为你的数据是正确的,因为它是相关的,所以我们不知道它属于哪里,而不是变量 canvas Game.canvas 与 Game 有关。另一件很棒的事情是您可以轻松创建新游戏:
var pong = Object.create( Game );
pong.initialize();
console.log( pong.canvas );
我是 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.
语法,所以我无法将这些解释联系起来。
我希望你能帮助我理解这行代码。
this指的是当前上下文。在这种情况下,上下文是 Game 对象。所以当你这样做时:
Game.initialize();
this 指的是 Game,因此所有内容都存储在 Game 中,例如:
Game.canvas
这特别有用,因为你的数据是正确的,因为它是相关的,所以我们不知道它属于哪里,而不是变量 canvas Game.canvas 与 Game 有关。另一件很棒的事情是您可以轻松创建新游戏:
var pong = Object.create( Game );
pong.initialize();
console.log( pong.canvas );