Defining JS modules

  • A JS file with a specific function
  • Encapsulate all data and functionality within a function (private)
  • Only one object or function containing n methods is exposed
  • The user of the module only needs to invoke the method of the object exposed by the module to realize the corresponding function

Define myModel

    function myModel() {
      var msg = 'Hello'
      function fun1() {
        console.log('fun1() ' + msg.toUpperCase)
      }
      function fun2() {
        console.log('fun1() ' + msg.toLowerCase)
      }
      // Exposed to the outside
      return {
        fun1: fun1,
        fun2: fun2
      }
    }
Copy the code

Reference myModel. Js

    <script type="text/javascript" src="myModel.js"></script>
    <script type="text/javascript">
      var model = myModel()
      model.fun1()
      model.fun2()
    </script>
Copy the code