I'm relatively new to JavaScript OOP and would like to know the best practice when doing a simple object such as a Model.
Here's a piece of code representing class named Child
:
What I'm asking for is:
- The usage of this (and the weak reference I'm doing which I name self)
- The global shape of the code (methods in prototype etc)
- Declaring a class as a function, or with JSON semantics
var Child = function( json ) {
var self = this;
// Properties
this.id = 0;
this.firstname = "";
this.moneyCurrent = 0;
this.moneyDue = 0;
this.missionsPlay = 0;
this.missionsWait = 0;
this.missionsStop = 0;
this.missions = [];
this.initialize( json );
}
Child.prototype = {
initialize: function( json ) {
var self = this;
self.id = json.id_child;
self.firstname = json.firstname;
self.moneyCurrent = parseFloat(json.already_paid) + parseFloat(json.to_pay) - parseFloat(json.spent_money);
self.moneyDue = parseFloat(json.to_pay);
self.missionsPlay = json.nb_missions.in_progress;
self.missionsWait = json.nb_missions.waiting;
self.missionsStop = json.nb_missions.completed;
},
getMissions: function( type, callback ) {
var self = this;
session.requestServer( "parent_getChildMissionList", {
sid: session.sid,
id_child: self.id,
status: type ? type : "",
strict_status: false,
page: 0
}, function( data ){
var missions = [];
$(data.missionList).each(function(){
self.missions.push(new Mission(this));
missions.push(self.missions[self.missions.length-1]);
});
callback( missions );
});
},
};
Classic way to declare a class:
var obj = function() {
var attribut = "foo";
this.metho = function(parameter1, parametre2) {
alert("parameters: " + parameter1 + ", " + parameter2);
}
}
JSON way to declare a class:
var obj = {
attribut: "foo",
method: function(parameter1, parameter2) {
alert("parameters: " + parameter1 + ", " + parameter2);
}
}