jeudi 16 février 2017

Immediately invoked object literal

What does this snippet of code do? What is its practical usage? I didn't write this code. I found it here: http://ift.tt/2lWXpWQ

!{
    //convenience methods here for create and expose via this
    create: function(options){
        //constructor logic here
        var created = Object.create(this.fn);
        var args = [].slice.call(arguments);
        this.plugins.forEach(function(plugin){
            plugin.apply(created, args);
        });
        return created;
    },
    fn:{//prototype methods here

    },
    expose:function(NameSpace, window, document, plugins){
        window[NameSpace] = this;//This can be tweaked for whatever
        this.document = document;
        this.plugins = plugins;
    }
}.expose("LibraryNamespace", window, document, []);

I am interested to know how is the above is any better than doing something like a revealing module pattern. Also I am unclear of the mechanism of the create function. Can someone walk me through the process of creating objects based on the prototypes passed in?

var libraryNameSpace= window.libraryNameSpace || {};
libraryNameSpace.myFeatureOne = (function(){
    var _bar = "_bar";
    var foo = "foo" + _bar;
    function foobar(){ return "foobar"; }
    return {
        myFoo : foo;
        fooBarMethod: foobar;
    };
})();

Aucun commentaire:

Enregistrer un commentaire