Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Javascript does not support inheritance by default?

As from OOPS base , I always use inheritance as a powerful tool for code reuse,

Example, if I write a chess program in OOPS and when I implement a is-a relationship as,

Class Piece{
  int teamColor;
  bool isLive;
  Positon pos;
  int Points; 
  .......
  int getTeamColor(){....}
  .......
};

Class Rook extend Piece{  //`is-a`
...... // No getTeamColor() definition here.. because the parent has the definition.
};

Class Pawn extend Piece{  //`is-a`
......// No getTeamColor() definition here.. because the parent has the definition.
};

I could do this with has-a relationship in javascript, but the drawback I am seeing is, I have to redefine every function in the derived class too.

Example : redefinition of getTeamColor() again in every rook,knight,pawn,king.... etc..

     var Pawn = function(teamColor,pos){
     var piece = new Piece(teamColor,pos);
     .......

     this.getTeamColor = function(){        
          return piece.getTeamColor();
    };
    }

My question is, Why javascript doesnot support classical inheritance as a default option?

like image 304
Muthu Ganapathy Nathan Avatar asked Apr 28 '13 08:04

Muthu Ganapathy Nathan


1 Answers

[Update in 2018] JavaScript now obviously supports inheritance with native language features.

class A { }
class B extends A { }

[/Update]

JavaScript does support inheritance on a prototypal way. What you need here is not classes but the encapsulation of behavior and the ability to override.

function Piece() { }

Piece.prototype.color = "white";
Piece.prototype.getColor = function() { return this.color }
Piece.prototype.move = function() { throw "pure function" };

function Pawn() { }
Pawn.prototype = new Piece();    
Pawn.prototype.move = function() { alert("moved"); }

and now:

var p = new Pawn(); p.color = "black";

> p instanceof Piece

true

 p instanceof Pawn

true

p.getColor()

"black"

p.move()

alert...

This is the basic approach and there are many libraries out there that turn this into something that is familiar for the guys wanting classes - so to say.

For example with JayData you can write the previous in a more encapsulated way (with the bonus of automatic constructor invocation up the chain:

var Piece = $data.Base.extend("Piece", {
  move: function()  {  throw "pure class" } 
});

var Pawn =  Piece.extend("Pawn", {
  move: function() { ... }
});

var p = new Pawn();
like image 149
Peter Aron Zentai Avatar answered Dec 14 '22 23:12

Peter Aron Zentai