Javascript – How to inherit a private member in JavaScript

inheritancejavascriptprivate-members

is there a way in JavaScript to inherit private members from a base class to a sub class?

I want to achieve something like this:

function BaseClass() {
  var privateProperty = "private";

  this.publicProperty = "public";
}

SubClass.prototype = new BaseClass();
SubClass.prototype.constructor = SubClass;

function SubClass() {
  alert( this.publicProperty );   // This works perfectly well

  alert( this.privateProperty );  // This doesn't work, because the property is not inherited
}

How can I achieve a class-like simulation, like in other oop-languages (eg. C++) where I can inherit private (protected) properties?

Thank you,
David Schreiber

Best Answer

Using Douglas Crockfords power constructor pattern (link is to a video), you can achieve protected variables like this:

function baseclass(secret) {
    secret = secret || {};
    secret.privateProperty = "private";
    return {
        publicProperty: "public"
    };
}

function subclass() {
    var secret = {}, self = baseclass(secret);
    alert(self.publicProperty);
    alert(secret.privateProperty);
    return self;
}

Note: With the power constructor pattern, you don't use new. Instead, just say var new_object = subclass();.