Tuesday, March 11, 2014

Simple JavaScript inheritance


Code:

function Person(name) {
        this.name = name;
}

Person.prototype.getName = function() {
        return this.name;
}

function Employee(name, salary) {
        Person.call(this, name);
        this.salary = salary;
}

Employee.prototype.__proto__ = Person.prototype;

Employee.prototype.getSalary = function() {
        return this.salary;
}

function Executive(name, salary, bonus) {
        Employee.call(this, name, salary);
        this.bonus = bonus;
}

Executive.prototype.__proto__ = Employee.prototype;

Executive.prototype.getBonus = function() {
        return this.bonus;
}

var workerbee = new Employee('Workerbee', 100000);
var hotshot = new Executive('Hotshot', 400000, 100000);

hotshot instanceof Executive => true
hotshot instanceof Employee => true
hotshot instanceof Person => true

workerbee instanceof Executive => false
workerbee instanceof Employee => true
workerbee instanceof Person => true

Picture:



Comments?

Other than use of __proto__  (bad! I know).

5 comments:

Martin Rinehart said...

Pretty good! I love the textless writing. Show, don't tell.

But are you sure about the word "inheritance"? In the C++ family languages (C++, Java, VB, C#, ...) a class inherits from another class. Our prototypes, at the first level, simply store the class instance methods. ('Employee', including 'Employee.prototype' is the equivalent of the C++ Employee class.)

And I would use constructor.prototype.

Martin (author: http://www.amazon.com/JavaScript-Inheritance-Object-Programming-Rinehart/dp/1490463046)

Sandip Chitale said...

@Martin, Thanks.

Yes, I am familiar with C++ and Java.

I did not understand the comment about constructor.prototype? Do you mean to say I should use:

Employee.prototype.constructor.prototype = Person.prototype;

?

If so that pollutes the prototype of the Person object with methods of Employee and even Executive.

Emilio said...

instead of writing

Employe.prototype.__proto__=...

yo can write:

Employe.prototype=Object.create(Person.prototype);

that solves many issues. (see http://www.crockford.com/)

Emilio said...

instead of writing

Employe.prototype.__proto__=...

yo can write:

Employe.prototype=Object.create(Person.prototype);

that solves many issues. (see http://www.crockford.com/)

Emilio said...

instead of writing

Employe.prototype.__proto__=...

yo can write:

Employe.prototype=Object.create(Person.prototype);

that solves many issues. (see http://www.crockford.com/)