Toby
Toby

Reputation: 8792

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.

Upvotes: 5

Views: 1743

Answers (3)

user2954463
user2954463

Reputation: 2401

Another reason to use a function instead of an object is if one of your defaults depends on a method in the model.

e.g.

defaults: function() {
    return {
        title: this.getTitle()
    }

Upvotes: 0

jakee
jakee

Reputation: 18566

I think there are not any performance difference between the 2 techniques you have described. The way the defaults is resolved (= function called or just the object returned) is decided by this line in underscore.js:

return _.isFunction(value) ? value.call(object) : value;

As for the benefits. The regular object offers a static way of declaring the model defaults. You declare them when extending and thats it, they won't change. The function on the other hand provides you with the ability to change the model defaults of the fly without re-creating the whole class, by modifying the object the function is supposed to return.

Upvotes: 1

twibakish
twibakish

Reputation: 149

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.

Upvotes: 6

Related Questions