Activity › Forums › Salesforce® Discussions › Why do we use Closure in Javascript?
-
Why do we use Closure in Javascript?
Posted by shafali on April 14, 2016 at 8:02 AMWhy do we use Closure in Javascript?
Parul replied 7 years, 7 months ago 4 Members · 3 Replies -
3 Replies
-
- [adinserter block='9']
-
I’ve used closures to do things like:
a = (function () {
var privatefunction = function () {
alert(‘hello’);
}return {
publicfunction : function () {
privatefunction();
}
}
})();As you can see there, a is now an object, with a method publicfunction ( a.publicfunction() ) which calls privatefunction, which only exists inside the closure. You can NOT call privatefunction directly (i.e. a.privatefunction() ), just publicfunction().
Its a minimal example but maybe you can see uses to it? We used this to enforce public/private methods.
-
Hi,
Because javascript doesn’t have feature like namespaces, and you can mess up pretty easily with all sort of global objects.
So it is important to be able to isolate some code in its own execution environment. Closure are perfect for that.
Hope this helps
Log In to reply.