Как сделать только определенные функции и переменные доступными глобально в Javascript, используя анонимные функции? - PullRequest
1 голос
/ 03 мая 2019

Предположим, у меня есть html-файл, имеющий структуру

<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>

Как мне убедиться, что во второй части <script> доступен только firstClass.init(), а не SecondClass()?

Я хотел бы использовать анонимные функции, такие как ;function({})();

Ответы [ 2 ]

3 голосов
/ 03 мая 2019

Создание экземпляра firstClass внутри IIFE, который содержит FirstClass, SecondClass и secret, и только возврат firstClass из 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>

Обратите внимание, что вам нужно использовать </script>, а не <scipt>, и вам нужно использовать new при вызове конструктора, чтобы использовать свойства, присвоенные this в конструкторе.

1 голос
/ 03 мая 2019

Этот фрагмент должен решить ваши потребности закрытия.

<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>
...