I'm using Bergi answer to this question: Inheritance and module pattern
I modified a bit the code to add _a
and _b
as private variables to test them... and I found a wrong behaviour I was expecting...
Parent = (function (a) {
var _a = null;
var _b = "b";
// constructor
function construct (a) {
console.log("Parent constructor - " + a);
_a = a;
};
// public functions
construct.prototype.getA = function () {
console.log("Parent: " + _a);
};
construct.prototype.getB = function () {
console.log("Parent: " + _b);
};
return construct;
})();
Child = (function () {
// constructor
function construct(b) {
console.log("Child constructor - " + b);
//Parent.apply(this, arguments);
Parent.call(this, "A");
_b = b;
}
// make the prototype object inherit from the Parent's one
construct.prototype = Object.create(Parent.prototype);
// public functions
construct.prototype.getB = function() {
console.log("Child: " + _b);
};
return construct;
})();
p = new Parent("a");
c = new Child("B");
c.getA(); // Parent: A -- nice!
c.getB(); // Parent: B -- nice!
p.getA(); // Parent: A -- wrong! "a" expected! (desired)
p.getB(); // Parent: b -- right
Is there any way to achieve the desired behaviour. A behaviour like java? maybe, where if you change the Child._a value, don't affect Parent._a like in this example.