0

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.

Community
  • 1
  • 1
danikaze
  • 1,550
  • 2
  • 16
  • 34

1 Answers1

1

IIFE is executed once on the declaration of Parent not every time you create an instance so _a is shared for all instances (try mutating arrays instead of assigning primitives). In Child there is no _b so you create a global _b.

The only way to create instance specific privates is to Have them in the constructor together with the privileged functions that need to access them. They will be inherited by doing Parent.call(this,args).

Because the privileged functions can't access the privates unless they're in the constructor body thus can't be on the prototype you have to sacrifice performance for instance specific privates.

More on constructor function, prototype and a pattern for protected can be found here.Prototypical inheritance - writing up

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160