0

I know there's no class in JS, but there's something like class, what is really weird for me. I'm quiet new to JS, and I'm trying to build a simple "class". This is how I tried:

Game = new function() {
   this.action_finish = 0;
   this.thick = function() {
      $('#action-finish').text(Game.action_finish--);
      setTimeout(this.thick, 1000);
   };
};

This is how it worked for me, and I'm wondering, why this.action_finish (returns NaN) does not work in thick function instead of Game.action_finish. Could anyone explain why does it work like this? I've been developing in PHP and C# for years an this approach is hard for me to understand.

Ps.: I don't need more instances of this class, and I'd like to use it like a class that's why I'm using the new keyword.

Edit: This is how I'm using it:

Game.action_finish = 10;
Game.thick();

Edit: Finally I solved my problem. As I tried to define my issue wasnt about the methods of declaring a class, but of reaching a class variable.

Here's the solution in case if anyone has the same problem:

this.thick.bind(this)

A little explanation can be found here: http://javascript.info/tutorial/binding

Kiss Koppány
  • 919
  • 5
  • 15
  • 33
  • Don't use `new function(){};` to create functions. Use `function Game(){}` or `var Game = function() {};`. Or `new Function(str)` to create a function from string, but better avoid that. – Oriol Nov 19 '14 at 23:30
  • 2
    Please check [this SO question](http://stackoverflow.com/questions/1114024/constructors-in-javascript-objects) it's exactly what you're looking for. (The `new` in your definition is not correct and you have to use prototypes to add methods to the class.) – AWolf Nov 19 '14 at 23:31
  • Isn't it correct the way I'm using it? – Kiss Koppány Nov 19 '14 at 23:33
  • What I'm asking is not the way of declaring, but why does this.action_finish not work INSIDE the class? Why do I have to use Game.action_finish instead of this.action_finish? – Kiss Koppány Nov 19 '14 at 23:34
  • 1
    @KissKoppány You don't have to use it. `Game` should be a function in order to use it as a constructor, but it's an object because of `new function()`. Then you should create instances using `new Game()`. Then `this.action_finish` will work. – Oriol Nov 19 '14 at 23:37

0 Answers0