new String(“foo”) instanceof String // this yields true “foo” instanceof String // this yields falseSo 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 trueSo 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 trueEverything 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 // trueNow the fun part. Let’s make a manager do some real works:
new Manager() instanceof WorkerBee // this yields trueWhat?!
1 comment:
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.
Post a Comment