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
Private Members in a SuperclassA subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
Private properties are not part of the prototypical inheritance model since they can only be accessed within the current class's body and aren't inherited by subclasses.
No, the private member are not inherited because the scope of a private member is only limited to the class in which it is defined. Only the public and protected member are inherited. A subclass does not inherit the private members of its parent class.
Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared. The answer is No. They do not.
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();
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With