Accessing private member variables from prototype-defined functions

前端 未结 25 1384
孤城傲影
孤城傲影 2020-11-22 14:48

Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods?

TestClass = function(){
    var priv         


        
25条回答
  •  清歌不尽
    2020-11-22 15:40

    I faced the exact same question today and after elaborating on Scott Rippey first-class response, I came up with a very simple solution (IMHO) that is both compatible with ES5 and efficient, it also is name clash safe (using _private seems unsafe).

    /*jslint white: true, plusplus: true */
    
     /*global console */
    
    var a, TestClass = (function(){
        "use strict";
        function PrefixedCounter (prefix) {
            var counter = 0;
            this.count = function () {
                return prefix + (++counter);
            };
        }
        var TestClass = (function(){
            var cls, pc = new PrefixedCounter("_TestClass_priv_")
            , privateField = pc.count()
            ;
            cls = function(){
                this[privateField] = "hello";
                this.nonProtoHello = function(){
                    console.log(this[privateField]);
                };
            };
            cls.prototype.prototypeHello = function(){
                console.log(this[privateField]);
            };
            return cls;
        }());
        return TestClass;
    }());
    
    a = new TestClass();
    a.nonProtoHello();
    a.prototypeHello();
    

    Tested with ringojs and nodejs. I'm eager to read your opinion.

提交回复
热议问题