I am just wondering if there is any drawbacks with the way I am tackling inheritance below ? Is there any memory leaks to consider, any more memory use than other inheritance patterns ? I prefer to code JavaScript with the "class" pattern below ( new ...() ) ... I find other inheritance patterns obtrusive, and just came up with this one...
Comments are appreciated!
// Class A
function A() {
var that = this;
that.hello = function() {
return "HELLO";
}
}
// Class B
function B() {
var zuper = new A();
var that = this;
that.variable = "VARIABLE";
zuper.bye = function () {
return "BYE";
}
zuper.getVariable = function() {
return that.variable
}
return zuper;
}
var b = new B();
alert ( b.hello() ) // "HELLO"
alert ( b.bye() ) // "BYE"
alert ( b.getVariable() ) // "VARIABLE"
================================ EDIT ================================= I have revised my original way, and came up with this. Does this suffer from the same problem as the one before ( Two objects created when creating a B, ( A and B total) ) See apply call in beginning of B
// Class A
function A() {
var that = this;
that.publicProperty = "PUBLIC_PROPERTY";
var privateProperty = "PRIVATE_PROPERTY";
that.hello = function() {
return "HELLO";
}
that.getPrivateProperty = function () {
return privateProperty;
}
that.overrideThis = function() {
return "NO_PLEASE_NO";
}
}
// Class B
function B(a, b, c) {
A.apply(this, arguments);
this.variable = "VARIABLE";
var privateVariable = "PRIVATE_VARIABLE";
this.bye = function () {
return "BYE";
}
this.getVariable = function() {
return this.variable
}
this.getPrivateVariable = function() {
return privateVariable;
}
this.getAandB = function() {
return a + b;
}
this.getFromSuperPublicPropery = function() {
return this.publicProperty;
}
this.overrideThis = function() {
return "MUHAHAHA";
}
}
var b = new B("aaa", "bbb");
alert ( b.hello() ) // "HELLO"
alert ( b.bye() ) // "BYE"
alert ( b.getVariable() ) // "VARIABLE"
alert ( b.getPrivateVariable() ) // "VARIABLE"'
alert ( b.getAandB() ) // "aaabbb"
alert ( b.getFromSuperPublicPropery() ) // "PUBLIC_PROPERTY"
alert ( b.getPrivateProperty() ) // "PRIVATE_PROPERTY"
alert ( b.overrideThis() ) // MUAHAHAA
function C() {
A.apply(this, arguments);
}
var c = new C();
alert ( c.overrideThis() ) // "NO_PLEASE_NO"
alert ( c.bye() ) // Expecting an exception here! Correct!