Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this design called?

I often see this pattern:

var suchAndSuch = new (function() {
    this.thing = "something";
    this.whoaLookAtThat = function() {
        return 4;
    }
    return {
        'thing' : thing,
        'whoaLookAtThat' : whoaLookAtThat
    }
})();

What is going on here? It's the return statement part that confuses the hell out of me.

I just don't get this particular use of an IIFE.

If nothing else, knowing what it's called would help me research it.

like image 522
temporary_user_name Avatar asked Mar 20 '23 20:03

temporary_user_name


2 Answers

This is a combination of an immediately executing function and a (bit of a messed up) closure. I think your example maybe a bit flawed it may be better if it was:

var suchAndSuch = (function() {
    var thing = "something";
    function setThing(newThing){
        //maybe do some error checking here
        thing = newThing;
    };
    function getThing(){
        return thing;
    };

    return {
        getThing : getThing,
        setThing : setThing
    }
})();

Then you would have a function that executes immediately returning a new object that effectively gives a private variable and an accessor function. I have used constructs like these many times.

like image 155
Aran Mulholland Avatar answered Mar 23 '23 12:03

Aran Mulholland


This is kind of an attempt to have public/private variables in JavaScript... I believe it is referred to as the modular pattern.

var suchAndSuch = (function() {
    var privateVariable = "something";
    var privateFunction = function() {
        return 4;
    }
    return {
        publicMethod1: function() {
            return privateVariable;
        },
        publicMethod2: function() {
            return privateFunction();
        }
    }
})();

Basically any variables declared inside the IIFE will be private. Then you return an object with methods. Since the object/methods were defined in the same scope as the private variables, the methods still have access to them. However, nothing else will.

like image 36
Jeff Shaver Avatar answered Mar 23 '23 11:03

Jeff Shaver