How to inherit a private member in JavaScript?

Is there a way in JavaScript to inherit private members from a base class to a subclass?

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 get cool modeling, for example, in other languages ​​of oop languages ​​(for example, C ++), where I can inherit private (protected) properties?

Thanks David Schreiber

+6
source share
5 answers

Using the Douglas Crockford power designer template (link to the video), you can get protected variables, for example:

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;
}

. new. var new_object = subclass();.

+13

- , _ , , ( )

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

. - , , .

0

, , :

SubClass.prototype.privateProperty  = undefined;

, , "private" .

0

, - ( 2019) javascript, WeakMap()

const _privateProperty = new WeakMap();

class BaseClass {
    constructor(){
        this.publicProperty = 'public';
       _privateProperty.set(this, 'private');
    }
}

module.exports = BaseClass;

const BaseClass = require('./BaseClass')

class ChildClass extends BaseClass{
   constructor(){
      super()
   }
}

Thus, your child class will inherit all public properties from BaseClass, except private ones.

Now I'm not sure whether to use this approach, but you can read private properties from your parent class through your child class as follows:

const _privateProperty = new WeakMap();

class BaseClass {
    constructor(){
        this.publicProperty = 'public';
       _privateProperty.set(this, 'private');
    }
    //Public method
    readProperties(){
      const property.private = _privateProperty.get(this);
      return property;
   }
}

module.exports = BaseClass;

Kids class

const BaseClass = require('./BaseClass')

class ChildClass extends BaseClass{
   constructor(){
      super()
   }
   //Public Method
   showProperties(){
      super.readProperties().private
   }
}

const properties = new ChildClass()
properties.showProperties()

0
source

All Articles