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?
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.
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.
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.
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.
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).
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!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With