Activity Forums Salesforce® Discussions Why do we use Closure in Javascript?

  • Naman

    Member
    April 14, 2016 at 8:05 am
  • Abhinav

    Member
    April 14, 2016 at 8:13 am

    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.

  • Parul

    Member
    September 19, 2018 at 11:47 pm

    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.

Popular Salesforce Blogs

Popular Salesforce Videos