0

I am a beginner in JavaScript and i don't quite understand a few things in the following script;

I am aware that Map, Player and App are classes and that map, player and app are instances of those three classes;

But why would you use the keyword "this" with the objects map and player and not just write instead var map = new Map() and var player = new Player()?

Any help will be highly appreciated!

var app;

var App = function() 
  this.map = new Map();
  this.player = new Player();
};

(function() {
  app = new App();
})();
R. Dee
  • 15
  • 3
  • 1
    BTW, there are no "classes" in Javascript, only objects and functions. You can write code which behaves similar enough to "classes" with constructors and "static" methods, but do not ever start to think that Javascript has classes. – deceze Sep 04 '15 at 10:25

2 Answers2

0
var App = function() 
  var map = new Map(),
      player = new Player();
};

Here map and player are available as variables inside the function only. In this particular code, there's nothing accessing those variables, so they'll fall out of scope immediately at the end of the function and will be removed.

var App = function() 
  this.map = new Map();
  this.player = new Player();
};

var app = new App();
app.map.foo();

Here map and player become properties of the instance of App and are accessible outside it and/or to other functions, like prototype functions of App.

deceze
  • 510,633
  • 85
  • 743
  • 889
0

Here this referring to the variable app. Benefit of using this is you will be able to access app.map() or app.player()

Prakash Laxkar
  • 824
  • 1
  • 8
  • 17