Suppose I have an html file that has the structure

<script>

let firstClass = new FirstClass();

var secret = 'code';

function FirstClass() {
    this.init = function () {
        console.log(SecondClass());
    }
}

function SecondClass() {
    return 'value';
}

</script>

// some html

<script>
    firstClass.init(); // should return a value
    console.log(secret); // should be undefined
    SecondClass(); // should not be accessible
    FirstClass(); // should not be accessible
</script>

How do I make sure that only the firstClass.init() is available from the second part of the <script> and not the SecondClass()?

I would like to use anonymous functions, like ;function({})();

2 Answers

3
CertainPerformance On Best Solutions

Instantiate firstClass inside an IIFE which contains FirstClass, SecondClass, and secret, and only return firstClass from the IIFE:

<script>
  const firstClass = (() => {
    const secret = 'secret';
    function FirstClass() {
      this.init = function() {
        console.log(SecondClass());
      }
    }

    function SecondClass() {
      return 'value';
    }
    return new FirstClass;
  })();
</script>


<script>
  firstClass.init(); // should return a value
  console.log(
    typeof secret,
    typeof SecondClass,
    typeof FirstClass
  );
</script>

Note that you need to use </script>, not <scipt>, and you need to use new when calling the constructor in order to use the properties assigned to this in the constructor.

1
Vinicius Dallacqua On

This snippet should solve your closure needs.

<script>
  (function (global) {
    const secret = 'code';
    
    function FirstClass() {
      this.init = function () {
        console.log(SecondClass());
      }
      
      return this;
    }

    const firstClass = FirstClass();

    function SecondClass() {
      return 'value';
    }

    global.firstClass = firstClass;
  })(window)
</script>
// some html

<script>
  firstClass.init(); // should return a value
  console.log(typeof secret); // should be undefined
  console.log(typeof SecondClass); // should be undefined
  console.log(typeof FirstClass); // should be undefined
</script>