Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inherit a private member in JavaScript?

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

like image 209
david.schreiber Avatar asked Nov 28 '09 17:11

david.schreiber


People also ask

Can you inherit private members?

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.

Are private fields inherited in JavaScript?

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.

Can private members be inherited Java?

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.

Are private field inherited?

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.


1 Answers

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

like image 76
Magnar Avatar answered Sep 19 '22 21:09

Magnar