views:

226

answers:

5

Hello,

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

A: 

I am not as good as I would like to be with Javascript, but IMHO what you call private property is not a property - it is just a variable on the stack. It disappers the moment control leaves your constructor.

IOW what you want is not possible.

mfeingold
A: 

This isn't possible. And that isn't really a private property - it's simply a regular variable that's only available in the scope in which it was defined.

J-P
A: 

That can't be done, but you could delete the property from the class prototype so that it is not inherited:

SubClass.prototype.privateProperty  = undefined;

That way it won't be inherited, but you need to do that for every "private" property in your base class.

Seth Illgard
A: 

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 )
Andris
A: 

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

Magnar
Thank you very much! The link to the power constructor pattern video helped me very much. This was exactly what I was looking for. Now I understand that there is much more for me to learn about JS and objects :-)
FMD