inheritance - Why people use prototype in javascript when it is easy to inherit using apply () and call () methods? -


shape inherited rectangle. inheritance can done many methods. here have used apply() , call (). when draw method child called, method draw method of base class called again. have done thing in 2 ways. 1 making prototype draw method of base class , other 1 using apply() , call() method.
first method :

function shape () {   this.name='shape';   this.getname = function () {    return this.name;   };   this.draw = function () {    alert("something");   }; }   function rectangle () {   shape.apply(this);   var x=this.draw;   this.name = 'rectangle';   this.id=500;   this.draw = function () {     x.call(this);   }; } 

second method :

function shape () {   this.name='shape';   this.id=100;   this.getname = function () {     return this.name;   }; }  shape.prototype.draw = function() {   alert("something"); };  function rectangle () {   this.name = 'rectangle';   this.id=200;     this.draw = function () {     shape.prototype.draw.call(this);   }; }  rectangle.prototype = new shape(); rectangle.prototype.constructor = rectangle; 

both of these 2 methods similar thing (in case of providing output). know using apply () , call () method can't directly access of base class's prototypes. inheritance using apply() , call() seems less complicated me. if both same why don't people use apply() , call() ? why need use prototypes ? problem face if don't use prototypes , inherit base classes using apply() , call () ??

inheritance gives ability use methods (and properties) of base class without having explicitly create them (or chain them) in derived class.

your "alternate" method require every method shape implements proxyed via every derived class if derived class not specialise method.

using prototype avoids this, because time call method or access property doesn't exist in derived class, js interpreter automatically traverses property chain until finds method in super class.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -