Monday, November 11, 2013

How to make a manager do some real works - javascript prototype, constructor, and instanceof

You probably heard about some ugly parts of javascript including the keyword “instanceof”. Just in case you missed, the followings are what I’m talking about.

new String(“foo”) instanceof String // this yields true
“foo” instanceof String             // this yields false
So some suggest that you stick with your own functions/objects (and classes if you believe they exist in javascript). The following is an example of how to make javascript play nice with classical OO.

function Employee() { this.name = “everyone”; }
function Manager() { this.name = “boss”; }
Manager.prototype = new Employee;
Now you may check that a manager is indeed a Manager and at the same time an Employee:

new Manager() instanceof Manager  // this yields true
new Manager() instanceof Employee // this yields true
So far so good.  Let's introduce worker, you known, the kind that do the real works.

function WorkerBee() { this.name = “worker”; }
WorkerBee.prototype = new Employee;
Let’s check that a worker is indeed a WorkerBee and at the same time an Employee:

new WorkerBee() instanceof WorkerBee // this yields true
new WorkerBee() instanceof Employee  // this yields true
Everything looks good. We have a classical OO inheritance defined using javascript prototypes.

As good citizens of developer community, we always follow some good principles (don’t we).  So to make the entire thing a little DRY,  let’s rearrange them like these:

function Employ() { this.name = “everyone”; }
function Manager() { this.name = “boss”; }
function WorkerBee() { this.name = “worker”; }
Manager.prototype = WorkerBeen.prototype = new Employee;

Satisfied?  (Do I hear some javascript Ninjas murmuring “noooooo…”? Ignore those noises.)  Let’s check them up.

new Manager() instanceof Manager     // true
new Manager() instanceof Employee    // true
new WorkerBee() instanceof WorkerBee // true
new WorkerBee() instanceof Employee  // true
Now the fun part.  Let’s make a manager do some real works:
new Manager() instanceof WorkerBee // this yields true
What?!

Reference

JavaScript Guide - Details of Object Model

1 comment:

karthik said...

Very good information. Its very useful for me. We need learn from real time examples and for this we choose good training institute, we need to learn from experts . So we make use of demo classes . Recently we tried java demo class of Apponix Technologies.