The last month I've been reading up on how to take my JavaScript code to the next level. I am a Java programmer at heart, so it feels nice when everything is encapsulated in classes/objects, and these are ready to be instantiated or inhertid or whatever.
I wrote a simple test project with the purpose to refine my techniques, and I'm feeling I can't do anything more with it. Would you guys and gals take a look at it?
var People = People || {};
People = (function() {
function People() {
this.people = [];
}
People.prototype.addGentleman = function (name) {
this.people.push(new People.Gentleman(name));
}
People.prototype.addLady = function (name, isMarried) {
this.people.push(new People.Lady(name, isMarried));
}
People.prototype.getList = function () {
var temp = [];
for (var i = 0; i < this.people.length; i++) {
temp.push(this.people[i].toString());
}
return temp;
}
return People;
})();
People.Human = (function () {
function Human(name, hasLadyParts) {
this.name = name;
this.hasLadyParts = hasLadyParts;
}
Human.prototype.hasLadyParts = function () {
return this.hasLadyParts;
}
Human.prototype.toString = function () {
var str = this.name + ' has ';
if (!this.hasLadyParts) str += 'no ';
return str + 'lady parts.';
}
return Human;
})();
People.Gentleman = (function () {
function Gentleman (name) {
People.Human.call(this, name, false);
}
Gentleman.prototype = Object.create(People.Human.prototype);
Gentleman.prototype.toString = function () {
return 'Mr. ' + People.Human.prototype.toString.call(this);
}
return Gentleman;
})();
People.Lady = (function () {
function Lady(name, hasWeddingRing) {
People.Human.call(this, name, true);
this.hasWeddingRing = hasWeddingRing;
}
function isNotMarried() {
return !this.hasWeddingRing;
}
Lady.prototype = Object.create(People.Human.prototype);
Lady.prototype.toString = function () {
var str = !isNotMarried.call(this) ? 'Mrs. ' : 'Ms. ';
return str + People.Human.prototype.toString.call(this);
}
return Lady;
})();
$(function () {
var people = new People();
people.addGentleman('Viktor');
people.addGentleman('Joakim');
people.addLady('Mattias', true);
var list = people.getList();
var $ul = $('#people');
for (var i = 0; i < list.length; i++) {
$ul.append('<li>' + list[i] + '</li>');
}
});
One question: can I create protected (or public) variables that my child instance can change? Besides that question I only want my code reviewed with regards to my Java context. It feels nice to have it like this, but what can I do better?
The code should be a pretty straight-forward OOP example, and here's a fiddle.