Exposing a method which is inside a closure

前端 未结 4 491
栀梦
栀梦 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 11:56

    You can return a reference to it...

    var a = function() {
    
       var b = function() {
          // I'm private!
          alert('go away!');
       };
    
       return {
          b: b // Not anymore!
       };
    
    };
    

    See it on jsFiddle.

    You could also bind it to the window object. But I prefer the method above, otherwise you are exposing it via a global variable (being a property of the window object).

提交回复
热议问题