Broad Network


ECMAScript Module Basics

ECMAScript Module Essentials – Part 1

Writing ECMAScript Module

Foreword: In this part of the series, I talk about ECMAScript Module Basics.

By: Chrysanthus Date Published: 24 Jul 2016

Introduction

This is part 1 of my series, ECMAScript Module Essentials. In this part of the series, I talk about ECMAScript Module Basics. A module is a file with commonly used functions. It may have a few variables. Different scripts (programs) written by different authors would use this same module.

Using a Module in a Script
Assume that the name of the module is modul.js . To use this module in your script, you will begin with:

    mod = require('./Modu.js');

where mod is an object representing the module and require is a reserved inclusion word for the module. mod is a name of your choice.  This statement assumes the module and your script are in the same directory; note the dot before /. If the module is in directory, c:/dir1/dir2, then the statement would become:

    mod = require('/dir1/dir2/Modu.js');

In your script, to use any variable or function from the module, you begin with mod, followed by the object dot, and then the name of the variable or function.

Exporting Variables
If you have a variable in a module, the script that uses the module has to be able to access the variable. To export a variable you need code like,

    var variab = 'value';
    exports.variab;

where exports is a reserved word.

In your script, you will get the value of the variable as follows:

    scriptVar = mod.variab;

Exporting a Function
In the module, to export a function, you need code like:

    exports.fn = function(args)
        {
            //statements
        }

In your script, to call the function, you will type:

    mod.fn(args);

If there is anything for the function to reurn, then you can do this:

    ret = mod.fn(args);

You can change the value of an exported variable in the module, from the script by having a set function in the module. So, if you want the script to chamge the variable, variab, above, you can have the module set function:

    exports.setFn = function (arg)
        {
            variab = arg;
        }

In the script you will type:

    mod.setFn('new value');

and this should change the value of variab from 'value' to 'new value', in the module.

That is it for this part of the series. We stop here and concinue in the next part.

Chrys

Related Links

Internet Socket and ECMAScript
Handling Bytes in ECMAScript
ECMAScript Bitwise Operators
ECMAScript Module Essentials
More Related Links
Node Mailsend
EMySQL API
Node.js Web Development Course
Major in Website Design
Low Level Programming - Writing ECMAScript Module
ECMAScript Course

NEXT

Comments

Become the Writer's Follower
Send the Writer a Message