Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it correct to invoke the constructor of a JavaScript Object in one of the prototype functions?

Tags:

javascript

oop

I am reviewing a JavaScript code from a colleague and he wrote an Object prototype function that I believe is not correct regarding the principles of Object-Oriented Programming.

Game.prototype.reset = function() {
    if (game.over) {
        game.over = false;
        game = new Game(players);
    }    
}

A couple of lines below, the game variable was declared as a global variable.

var game = new Game(players);

So, is it correct to create a new Game object from one of its constructors? The code perfectly runs. Thanks!

like image 718
Jose Avatar asked May 15 '15 15:05

Jose


2 Answers

He should not reference the variable game inside the prototype method, as game is the name of the instance. Instead he should use this to refer to the current object.

Inside the reset method he should not created the new game instance but truly reset the Game fields, something along below:

Game.prototype.reset = function() {
    if (this.over) {
        this.over = false;
        this.initialize(this.players);
    }    
}

Game.prototype.initialize = function(players) {
    this.players = players;
    :
}
like image 136
MaxZoom Avatar answered Oct 07 '22 01:10

MaxZoom


I guest this broke the encapsulation principle, each instance is responsable to deal with his own behavior, not with other global instance.

http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)

If was me, i would choose Max Zoom alternative to model my solution.

like image 33
jeronimo vallelunga Avatar answered Oct 07 '22 00:10

jeronimo vallelunga