DEV Community

Vishang
Vishang

Posted on

1

Use of IIFE to Create a Module

An immediately invoked function expression (IIFE) is often used to group related functionality into a single object or module. For example, let's consider we need to wrap this two mixins in a module.


function glideMixin(obj){
    obj.glide = function(){
        console.log("Gliding on the water");
    };    
}

function flyMixin(obj){
    obj.fly = function(){
        console.log("Flying Woohoo");
    };
}

we can group this two mixin in a module using IIFE. See below how can we do that.


let motionModule = (function(){
    return {
        glideMixin: function(obj){
            obj.glide = function(){
                console.log("Gliding on the water");
            };
        },
        flyMixin: function(obj){
            obj.fly = function(){
                console.log("Flying Woohoo");
            };
        }
    }
})();

Note that you have an immediately invoked function expression (IIFE) that returns an object motionModule. This returned object contains all of the mixin behaviors as properties of the object.

The advantage of the module pattern is that all of the motion behaviors can be packaged into a single object that can then be used by other parts of your code. Here is an example using it:

motionModule.glideMixin(anyObject);
anyObject.glide();

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay