Search code examples
backbone.js

Should my Backbone defaults be an object or a function?


I have been reading and following several Backbone.js tutorials and when it comes to defaults for the model people seem to do it one of two ways.

First Way - Defaults are an object

The first way is that defaults are declared as an object, for example;

my_model = Backbone.Model.extend({
    defaults: {
        title: 'Default Title'
    }
});

This makes most sense to me, I immediately know that the defaults is an object and it works fine.

Second Way - Defaults are a function

The second way I have seen this is is that defaults are declared as a function, for example;

my_model = Backbone.Model.extend({
    defaults: function() {
        return {
            title: 'Default Title'
        }
    }
});

This function obviously ends up returning an object, and to me makes little sense (unless you wanted to pass something into the function eventually.

My Question

My question is, is there a benefit to using one over the other assuming that you will not be passing any parameters using the function way. My feeling is that there may be a minuscule overhead from having the anonymous function be called but would love a more informed opinion.


Solution

  • Remember that in JavaScript, objects are passed by reference, so if you include an object as a default value, it will be shared among all instances. Defaults containing objects passed by reference should be defined using a function if you do not wish to share objects between all instances

    https://github.com/documentcloud/backbone/issues/1145

    Pretty much sums it up. The function method is only recommended when you have object attributes.