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

Steps to Connect Pardot to Salesforce

Steps to Connect Pardot to Salesforce

Blog in

Steps to Integrate Salesforce and Pardot: There are some steps to install Pardot in salesforce 1- Click on this link https://login.salesforce.com/?ec=302&startURL=%2Fpackaging%2FinstallPackage.apexp%3Fp0%3D04t1W000000U7P8(production) https://test.salesforce.com/?ec=302&startURL=%2Fpackaging%2FinstallPackage.apexp%3Fp0%3D04t1W000000U7P8 (sandbox) 2- After…

Popular Salesforce Videos