Inheritance can be done through a prototype. First, add properties and methods to the parent prototype. Second, set the child prototype to the parent object. Third, set constructor for child class, because by defualt will be parent constructor. If necessary override the parent methods.
Since ECMAScript 2015 more classical syntax available.
//---------------------
// parent class
class Figure {
constructor(){
this.xPos = 100;
this.yPos = 100;
this.toString = function(){
return JSON.stringify(
{x: this.xPos, y: this.yPos });
}
};
}
// check, log string will be
// pos={"x":100,"y":100}
var figure = new Figure();
console.log(`pos=${figure.toString()}`);
//------------------------------
// child class
class Rectangle extends Figure {
constructor(width, height){
super();
this.width=width;
this.height=height;
this.toString = function(){
return JSON.stringify({
x: this.xPos,
y: this.yPos,
width: this.width,
height: this.height
});
}
}
}
// check, out string will be
// rect={"x":100,"y":100,"width":60,"height":200}
var rect = new Rectangle(60, 200);
console.log(`rect=${rect.toString()}`);
//-----------------------
// parent class
function Figure(){}
Figure.prototype.xPos = 100;
Figure.prototype.yPos = 100;
Figure.prototype.toString = function(){
return JSON.stringify(
{x: this.xPos, y: this.yPos });
}
// check, log string will be
// pos={"x":100,"y":100}
var figure = new Figure();
console.log(`pos=${figure.toString()}`);
//-----------------------
// child class
Rectangle.prototype = new Figure();
Rectangle.prototype.constructor = Rectangle;
function Rectangle(width, height){
this.width = width;
this.height = height;
}
// override methods
Rectangle.prototype.toString = function(){
return JSON.stringify({
x: this.xPos,
y: this.yPos,
width: this.width,
height: this.height
});
}
// check, log string will be
// rect={"x":100,"y":100,"width":60,"height":200}
var rect = new Rectangle(60, 200);
console.log(`rect=${rect.toString()}`);