[Home]Javascript/Modules

UseModWiki | Javascript | RecentChanges | Preferences

Modules

Problems

Consider

  <script src="a.js></script>
  <script src="b.js></script>
  <script>
     var b = new B();
     b.g();
     </script>

where a.js is

 A.prototype.f = A_f;
 function A() {}
 function A_f { ... helper_func(); ... }
 function helper_func() {}
b.js
 B.prototype = new A()
 B.prototype.g = B_g;
 function B() {}
 function B_g() {... helper_func(); ... }
 function helper_func() {}

Problems:

  1. The HTML file script src= statements should be written in the right order, because of dependencies between a.js and b.js. This knowledge though, is internal to a.js and b.js
  2. The function helper_func gets redefined in b.js

Solution

The solution to these 2 problems is borrowed from more developed (in this respect) languages, particularly, from python.

Module is a minimal unit of code that can be loaded and can export symbols defined in it. a.js would ideally look like:

 module a 
     {
     A.prototype.f = A_f;
     function A() {}
     function A_f { ... helper_func(); ... }
     function helper_func() {}
     export A
     }

b.js

 module B 
     {
     symbols = import module a;
     B.prototype = new symbols.A()
     B.prototype.g = B_g;
     function B() {}
     function B_g() {... helper_func(); ... }
     function helper_func() {}
     export B;
     }
.html file
    <script src="b.js"></script>
    <script src="a.js"></script>
    <script>
         symbols = import module b;
         var b = new symbols.B();
         b.g();
         </script>
This requires
  language construct import module module_name
  language construct module <module_name> { ...  } 

The packages are the part of ECMAscript 4 (under development and not yet complete) and JScript.NET (Cannot be used in any hosts but ASP.NET) This leaves us with the options of writing the above in terms of existing Javascript features. The

  module <module_name> { ... <exported symbols>; } 
becomes
  module( "<module_name>", function() { 
  ...
  module body
  ...
  return <exported symbols>
  } )
and
 import module module_name
becomes
  function import_module( module_name ) { ... }

Usage example

file union.js

 module( "union", function() {
     function union()
         {
         }
     return { union: union }; // exported symbols
     }  
file difference.js
 module( "difference", function() {
     function difference()
         {
         }
     return { difference: difference }; // exported symbols
     }  
    }
.html file
 <script>
     var difference = import_module( "difference" ).difference;
     var union = import_module( "union" ).union;
     union( [1, 2, 3, 4], difference( [5, 6, 7], [ 5, 6 ] ) )
     </script>

See [/Namespaces] section for a better version of this approach.


UseModWiki | Javascript | RecentChanges | Preferences
Edit text of this page | View other revisions | Search MetaWiki
Last edited February 23, 2003 4:54 am by Mbergal (diff)
Search: