How to inherit a private member in JavaScript?

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();.


Mark your private variables with some kind of markup like a leading underscore _ This way you know it's a private variable (although technically it isn't)

this._privateProperty = "private";
alert( this._privateProperty )