JSFiddle - React, Tailwind, and code Playground

by Aaron Zhang

JavaScript

var CLASS = function () {
    this.publicFunctions = {};
    this.PROTOTYPE = {};
    var _class = function () {
        this.constructor.apply(this, arguments);
    };
    _class.prototype = this.PROTOTYPE;
    _class.prototype.validateAccess = CLASS.prototype.validateAccess;
    _class.prototype.constructor = function () {};
    _class.prototype.publicFunctions = this.publicFunctions;
    this.finalClass = _class;

    return this;
};

CLASS.prototype.validateAccess = function (caller) {
    if (this.publicFunctions[caller] !== caller) {
        throw 'Accessing private functions from outside of the scope';
    }
    return true;
};
CLASS.prototype.setConstructor = function (func) {
    this.PROTOTYPE.constructor = func;
};
CLASS.prototype.addPrivateFunction = function (name, func) {
    this.PROTOTYPE[name] = function () {
        this.validateAccess(this[name].caller);
        func.apply(this, arguments);
    };
    return this;
};

CLASS.prototype.addPublicFunction = function (name, func) {
    this.PROTOTYPE[name] = func;
    this.publicFunctions[this.PROTOTYPE[name]] = this.PROTOTYPE[name];
    return this;
};


CLASS.prototype.getClass = function () {
    return this.finalClass;
};


var _person = new CLASS();
_person.addPrivateFunction('privateSayHi', function () {
    alert('Hi ' + this.name + '!');
});
_person.addPublicFunction('publicSayHi', function () {
    this.privateSayHi();
});
_person.addPublicFunction('publicSetName', function (val) {
    this.name = val;
});

_person.setConstructor(function (name) {
    this.name = name;
});


var Person = _person.getClass();

var p1 = new Person('Aaron');
var p2 = new Person('Brian');
p1.publicSayHi();
p2.publicSayHi();

p1.privateSayHi(); //error comes from here, accessing the member function from outside of the scope.