Private variables

Using private variables with inheritable prototype.

by oceog

JavaScript

(function (exports) {
    /*
     * sample prototype,
     *
     * inherit @boolean if true - return privates object,
     *
     */
    function A(inherit) {
        var privates = { //setup private vars, they could be also changed, added in method or children
            a: 1,
            b: 2,
            c: 3
        };
        //setup public methods which uses privates
        this.aPlus = bindPlus("aPlus", this, privates); //pass method name as string!
        this.aGet = bindPlus("aGet", this, privates);
        if (inherit) {
            return privates;
        }
    }
    A.prototype.aPlus = function () {
        var args = getArgs(arguments),
            //self is "this" here (applied/called too), object reference is still this        
            privates = args.shift(),
            self = args.shift(),
            //function real arguments            
            n = args.shift();
        return privates.a += n;
    };

    A.prototype.aGet = function (n) {
        var args = getArgs(arguments),                
            privates = args.shift(),
            self = args.shift();        
        console.error(this, self,privates);
        return privates.a;
    };

    exports.A = A;
    exports.getArgs = getArgs; //should be hidden somehow, but his is out of the story
    exports.bindPlus = bindPlus;


    //utilites
    function getArgs(arg) {
        return Array.prototype.slice.call(arg);
    }

    function bindPlus(funct, self, privates) {
        /**
        * if uncomment here and comment same line later,
        * it will be run faster, but it would be impossible 
        * to change prototype after constructor run (tests after ----- could be incorrect)
        */
        
        //var func=Object.getPrototypeOf(self)[funct].bind(self, privates);
        return function () {                        
            var func=Object.getPrototypeOf(self)[funct].bind(self, privates);
            var args=getArgs(arguments); //this could be changed...