Inheritance with operator new
The traditional (ES3 and earlier) approach to inheritance in JavaScript.
by Ray Toal
HTML
<script src="http://code.jquery.com/qunit/git/qunit.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/git/qunit.css">
<h1 id="qunit-header">Shape Tests</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<ol id="qunit-tests"></ol>
JavaScript
var Person = function (name, birthdate) {
this.name = name;
this.birthdate = birthdate;
};
/*
* Returns the age, in years, of the person. Assumes a year
* of 365.2522 days and does not worry about leap seconds.
*/
Person.prototype.age = function () {
return (Date.now() - this.birthdate) / 1000 / 86400 / 365.2522;
};
var Employee = function (name, birthdate, employer, hiredate, salary) {
Person.call(this, name, birthdate);
this.employer = employer;
this.hiredate = hiredate;
this.salary = salary;
};
/*
* This builds the prototype chain, so all employees can also
* have methods from Person.prototype. Of course, the new
* prototype employee has useless name and birthdate fields,
* and the constructor property isn't set right, but we could,
* with extra effort, deal with these issues.
*/
Employee.prototype = new Person();
test("Simple employee test", function () {
var alice = new Employee("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);
});