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's going on here? This is the part of the statement returnthat drives me crazy.

I just do not use this use of IIFE.

If nothing else, knowing what he called, it will help me explore it.

+4
source share
3 answers

This is a combination of an immediately executed function and closure (bit corrupted). I think your example might be a little messed up, maybe it would be better if it were:

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 will have a function that immediately launches a new object that effectively gives a private variable and an access function. I have used such designs many times.

+5
source

/ JavaScript... , .

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

, , IIFE, . . / , , . .

+1

. JS , , , . , , (bla)() - , . , .

The practice of returning an object other than the created newone is what I sometimes see as a way to protect code that forgets newand simply calls the constructor. In this context, however, it makes no sense to assign properties this, since it thisis an object window. Otherwise, if you use new, the thisGC is immediately reset, so it still makes no sense.

+1
source

All Articles