Accessing private member variables from prototype-defined functions

前端 未结 25 1245
孤城傲影
孤城傲影 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:28

    Here's what I came up with.

    (function () {
        var staticVar = 0;
        var yrObj = function () {
            var private = {"a":1,"b":2};
            var MyObj = function () {
                private.a += staticVar;
                staticVar++;
            };
            MyObj.prototype = {
                "test" : function () {
                    console.log(private.a);
                }
            };
    
            return new MyObj;
        };
        window.YrObj = yrObj;
    }());
    
    var obj1 = new YrObj;
    var obj2 = new YrObj;
    obj1.test(); // 1
    obj2.test(); // 2
    

    the main problem with this implementation is that it redefines the prototypes on every instanciation.

提交回复
热议问题