prototype JS class inheritance
by Ben Clayton
JavaScript
function classx() {
this.ma = function() {
return "xa "
}
this.mb = function() {
return "xb "
}
this.mc = function() {
return this.ma() + this.mb()
}
}
function classy() {
this.ma = function() {
return "ya "
}
}
classy.prototype = new classx;
var x = new classx;
var y = new classy;
console.log("classx called", x.mc())
console.log("classx called", y.mc())
//======================================================================
class davex {
constructor() {
this.x = 1;
}
ma() {
return (this.x + 'xa');
}
mb() {
return (this.x + 'xb');
}
turkey() {
var e = 'raw ';
if (this.x == 1) {
e += this.ma();
} else {
e += this.mb();
}
return e;
}
stuff() {
var e = this.turkey();
return e;
}
}
class ben extends davex {
constructor() {
super();
this.x = 10;
}
ma() {
return ('the world has ended' + this.x);
}
turkey() {
var e = '';
e = super.turkey() + ' now cooked ';
if (this.x > 10 ) {
e += super.ma();
e += this.ma();
} else {
e += this.mb();
}
return e;
}
}
class sam extends davex {
constructor() {
super();
this.x = 2;
}
ma() {
return (super.ma() + 'sam dinner' + this.x);
}
mb() {
return ('feel ill too much turkey');
}
turkey() {
var e = '';
e = super.turkey() + ' now consumed ';
if (this.x > 20 ) {
e += this.ma();
} else {
e += this.mb();
}
return e;
}
}
jow = new ben();
jiw = new davex();
sammy = new sam();
console.log('ben ' + jow.stuff());
jow.x = 1;
console.log('ben ' + jow.stuff());
jow.x = 11;
console.log('ben ' + jow.stuff());
console.log('davex ' + jiw.stuff());
jiw.x = 1;
console.log('davex ' + jiw.stuff());
jiw.x = 11;
console.log('davex ' + jiw.stuff());
console.log('sammy ' + sammy.stuff());
sammy.x = 1;
console.log('sammy ' + sammy.stuff());
sammy.x = 21;
console.log('sammy ' + sammy.stuff());