Exposing a method which is inside a closure

前端 未结 4 495
栀梦
栀梦 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:54

    You need to pass it to the outside in some manner.

    Example: http://jsfiddle.net/patrick_dw/T9vnn/1/

    function someFunc() {
    
        var privateFunc = function() {
            alert('expose me!');
        }
    
        // Method 1: Directly assign it to an outer scope
        window.exposed = privateFunc;
    
        // Method 2: pass it out as a function argument
        someOuterFunction( privateFunc );
    
        // Method 3: return it
        return privateFunc;
    }
    
    someFunc()(); // alerts "expose me!"
    
    function someOuterFunction( fn ) {
        fn(); // alerts "expose me!"
    }
    
    window.exposed(); // alerts "expose me!"
    

提交回复
热议问题