IIFE is the foundation of modern modularisation in frontend development!

1
2
3
4
5
let module = (function(){
let _private = "hi, anran!";
let fun = ()=>{console.log(_private);}
return {fun}
})()

here module is an immediately-invoked function expression. The _private variable will not be available outside of the module. To log the _private message in the console, run:

1
module.fun();

You cannot get the _private message by running

1
module._private

This isolated scope decreases the chance of global pollution. However, it could contain functions but not properties. This is when frontend modularisation protocols come in.

Next Step

  • Get more clear about how ES6 enables modularisation, why it needs to work with webpack to function to its full power.

  • Node.js modules:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // square.js
    // Assigning to exports will not modify module, must use module.exports
    module.exports = class Square {
    constructor(width) {
    this.width = width;
    }

    area() {
    return this.width ** 2;
    }
    };
1
2
3
4
// bar.js
const Square = require('./square.js');
const mySquare = new Square(2);
console.log(`The area of mySquare is ${mySquare.area()}`);