Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exposing a method which is inside a closure

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?

like image 860
paul Avatar asked Dec 10 '10 01:12

paul


People also ask

What is closure give an example?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.

What are closures few common uses for closures?

Closures are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.

How would you use a closure to create a private counter?

3How would you use a closure to create a private counter? You can create a function within an outer function (a closure) that allows you to update a private variable but the variable wouldn't be accessible from outside the function without the use of a helper function.

How do closures work?

A Closure is a combination of a function enclosed with references to its surrounding state (the lexical environment). In JavaScript, closures are created every time a function is created at run time. In other words, a closure is just a fancy name for a function that remembers the external things used inside it.


2 Answers

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).

like image 101
alex Avatar answered Oct 05 '22 23:10

alex


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!"
like image 34
user113716 Avatar answered Oct 05 '22 23:10

user113716