-1

I'm very new in javascript. I play on codepen.io to learn some javascript project. I found Pong-JS implementation. I found something that i cant figure it out. Because i don't know what kind of thing it's

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

My question why it use this. to make some variable. Why not use var? Because i find out about this. syntax and i can't relate those explanation. I hope you can help me understand this line of code.

here is the codepen : https://codepen.io/gdube/pen/JybxxZ?editors=1010

1 Answers1

-1

this refers to the current context. The context is the Game object in this case. So when you do:

Game.initialize();

this refers to Game, so everything gets stored inside of Game, e.g.:

Game.canvas

This is especially useful as your data is right were it is related to, so instead of a variable canvas we dont know where it belongs to, we know that Game.canvas is related to Game. Another cool thing is that you can create new Games easily:

var pong = Object.create( Game );
pong.initialize();
console.log( pong.canvas );
Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
  • If i'm not wrong, i must refer to Object to to store data. Then when you use var? Appreciate your brief explanation sir. It was good one :) – Hasby Fahrudin Aug 19 '17 at 10:22
  • @hasby fahrudin just use variables ( inside functions) to store values that are just accessible inside the function and can be easily deleted afterwards. – Jonas Wilms Aug 19 '17 at 10:27