Accessing private member variables from prototype-defined functions

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

    var getParams = function(_func) {
      res = _func.toString().split('function (')[1].split(')')[0].split(',')
      return res
    }
    
    function TestClass(){
    
      var private = {hidden: 'secret'}
      //clever magic accessor thing goes here
      if ( !(this instanceof arguments.callee) ) {
        for (var key in arguments) {
          if (typeof arguments[key] == 'function') {
            var keys = getParams(arguments[key])
            var params = []
            for (var i = 0; i <= keys.length; i++) {
              if (private[keys[i]] != undefined) {
                params.push(private[keys[i]])
              }
            }
            arguments[key].apply(null,params)
          }
        }
      }
    }
    
    
    TestClass.prototype.test = function(){
      var _hidden; //variable I want to get
      TestClass(function(hidden) {_hidden = hidden}) //invoke magic to get
    };
    
    new TestClass().test()
    

    How's this? Using an private accessor. Only allows you to get the variables though not to set them, depends on the use case.

提交回复
热议问题