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!
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;
:
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With