Exposing a method which is inside a closure

前端 未结 4 489
栀梦
栀梦 2021-02-07 11:21

When we are creating a method inside a closure it becomes private to that closure and can\'t be accessed until we expose it in some way.

How can it be exposed?

4条回答
  •  生来不讨喜
    2021-02-07 12:09

    For performance purposes you can invoke it this way:

    var a = (function(){
       function _a(){}
       _a.prototype = (function(){
         var _test = function(){ console.log("test"); };
         return {
           test: _test
         }
       }());
    
      return new _a();
    }());
    
    // usage
    var x = a;
    x.test(); // "test"
    

提交回复
热议问题