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.
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.
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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With