DEV Community

Discussion on: Classes in JS: Public, Private and Protected

Collapse
 
obscerno profile image
Obscerno • Edited

Have fun! I'd like to add that in practice I'd probably not go to these length to protect the variables unless it was absolutely necessary. I'd probably do something more like:

// This is the object we want to inherit from.
function Base(param1, _) {
    var _this = this;
    var shared = _ || {};

    // Declare class variables and functions like this:
    this.foo = "Anyone can access this!";

    shared.bar = function() {
        console.log(secret());
        return "Shared function accessed!";
    };

    var secret = function() {
        // _this is needed to access object in private functions, otherwise leave out.
        return _this.foo;
    };
}

// Inherits from Base
function Derived(param1) {
    // Inherit
    var shared = {};
    Base.call(this, param1, shared);

    // Outputs "Shared function accessed!"
    console.log(shared.bar());
}

// Exclude shared param when not inheriting.
var myBase = new Base("param1");
var myDerived = new Derived("param1");
Enter fullscreen mode Exit fullscreen mode

Yo use it the same, you just have to trust people not to pass in a _ argument on construction to snatch the shared variables. I think it's a step up from defining public variables like this._myProtectedVar, but it's not technically protected (which is why I call the variable shared inside the function).