Is there a good reason for wrapping an extra immedeately-invoked function around a requireJS module definition?

StackOverflow https://stackoverflow.com/questions/8813215

Pergunta

I was looking at the Backbone-requireJS boilerplates in GitHub, I see two different types of implementations.

https://github.com/david0178418/BackboneJS-AMD-Boilerplate/blob/master/src/js/views/viewStub.js has the following as the viewStub:

function() {
    "use strict";

    define([
            'jqueryLoader',
            'underscore',
            'backbone',
        ],
        function($, _, Backbone) {

            return Backbone.View.extend({
                template : _.template(/*loaded template*/),

                initialize : function() {
                    this.render();
                },

                render : function() {
                    $(this.el).append(this.template(/*model/collection*/));

                    return this;
                }
            });
        }
    );
})();

Whereas the view-stub from the other boilerplate https://github.com/jcreamer898/RequireJS-Backbone-Starter/blob/master/js/views/view.js has the following:

define([
        'jquery', 
        'backbone',
        'underscore', 
        'models/model',
        'text!templates/main.html'], 
function($, Backbone, _, model, template){
    var View = Backbone.View.extend({
        el: '#main',
        initialize: function(){
            this.model = new model({
                message: 'Hello World'
            });
            this.template = _.template( template, { model: this.model.toJSON() } );
        },
        render: function(){
            $(this.el).append( this.template );
        }
    });

    return new View();
}); 

My question here is: Why is there a self-executing function around the whole RequireJS module in the first example?

Foi útil?

Solução

There doesn't need to be a containing closure in this example. It creates a scope so that declared variables or functions don't leak into the global scope. But when you are not creating variables or named functions, then there is nothing to leak. So there isn't much point.

The real reason may be simpler than you think. Like using the turn signal even if noone is around, enclosing every JS source file in a self executing function is a good habit to get into. It saves you from stupid mistakes. So it may just be an example of a defensive programming style.

There is no benefit in this example, but the related performance cost at runtime is totally negligible. So why not do it the "right" way in case some one new comes in and "maintains" this module in some funky ways?

Outras dicas

There is totally no point in doing this, because you already have a function that creates its own namespaces.

Moreover there is a disadvantage - you are getting an extra indent, so your code becomes less readable.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top