Fortgeschrittene OO-Programmierung in Javascript

Listing 1 - 3

Listing 1: Einfache Objekte

function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.getName = function() {
return this.firstName + " " + this.lastName;
};
}
var testPerson = new Person("Max", "Muster");
alert(testPerson.getName());

Listing 2: Methoden per Prototyp

function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.getName = function() {
return this.firstName + " " + this.lastName;
};
var testPerson = new Person("Max", "Muster");
alert(testPerson.getName());

Listing 3: Vererbung per Prototyp

// Definition von "Person" wie in Listing 2
function Employee(firstName, lastName, department) {
Person.call(this, firstName, lastName);
this.department = department;
};
Employee.prototype = new Person();
Employee.prototype.getName = function() {
return Person.prototype.getName.call(this) +
" (" + this.department + ")";
};
Employee.prototype.alertName = function() {
alert(this.getName());
};
var max = new Employee("Max", "Muster", "Sales");
max.alertName();