Inheritance
An approach to JavaScript inheritance in which type objects are prototypes and creation functions are properties just like other methods.
by Ray Toal
HTML
<script src="http://code.jquery.com/qunit/qunit-git.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-git.css">
<div id="qunit"></div>
<div id="qunit-fixture"></div>
JavaScript
/*
* A person datatype.
*/
var Person = {};
Person.create = function (name, birthdate) {
var person = Object.create(this);
person.name = name;
person.birthdate = birthdate;
return person;
};
/*
* Returns the age, in years, of the person. Assumes a year
* of 365.2522 days and does not worry about leap seconds.
*/
Person.age = function () {
return (Date.now() - this.birthdate) / 1000 / 86400 / 365.2522;
};
/*
* An employee datatype. Employee is a subtype of Person.
*/
var Employee = Object.create(Person);
Employee.create = function (name, birthdate, employer, hiredate, salary) {
var employee = Object.create(this);
employee.name = name;
employee.birthdate = birthdate;
employee.employer = employer;
employee.hiredate = hiredate;
employee.salary = salary;
return employee;
};
QUnit.test("Simple employee test", function () {
var alice = Employee.create("Alice", new Date(2000, 0, 1),
"Bob", new Date(2012, 0, 1), 50000);
equal(alice.name, "Alice");
ok(alice.age() > 12);
ok(alice.age() < 1000);
equal(alice.employer, "Bob");
deepEqual(alice.hiredate, new Date(2012, 0, 1));
equal(alice.salary, 50000);
});