oop - How to extend a class in JavaScript -
i'm working on chess game built in javascript. i'm taking object-oriented approach , having difficulty working javascript's inheritance. want there "piece" abstract class holds fields , basic getters/setters such piece black or white. want have classes each type of piece can instantiate so:
var pieceone = new pawn();
the pawn() should have fields , methods of piece have own method movement, , additional fields (such whether or not has moved yet, doesn't matter pieces). here's current piece class:
//this object specifies basic information pieces. "use strict"; function piece(color, type, captured, hasmoved) { this.color = color; this.type = type; this.captured = captured; this.hasmoved = hasmoved; this.image = color + "_" + type + ".svg"; } piece.prototype.getimage = function getimage(){ return this.image; } piece.prototype.iscaptured = function iscaptured(){ return this.captured; };
i know if going make subclass every kind of piece i'd eliminate "type" field, how make pawn subclass? this?
function pawn() = new piece(color, captured, hasmoved); pawn.prototype.getlegalmoves = function getlegalmoves(){ //return legal moves } var pieceone = new pawn("black", false, false);
if willing take object oriented approach on js recommend follow power constructor pattern.
basically have function creates objects , take advantage of closures hide internal properties (fields or methods).
function myobject(){ var that={}; var myprivatefield; var myprivatefunction=function(){ } that.mypublicmethod=function(){ } return that; }
then can call method myobject() , new object of type.
you can extend example use inheritance calling power constructor of object , use object augmentation. take @ example of parasatic inheritance of douglas crockford.
Comments
Post a Comment