Should my base ones be an object or function by default?

I read and followed several Backbone.js tutorials, and when it comes to model defaults, people seem to do this in one of two ways.

The first way - the default values ​​are objects

The first way is that the default values ​​are declared as an object, for example:

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

This makes sense to me, I immediately know that by default this is an object and it works great.

The second way - default values ​​- is a function

The second way I've seen is that the default values ​​are declared as a function, for example:

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

This function, obviously, completes the return of the object, and for me there is little point (if you do not want to somehow pass something to the function.

My question

My question is whether there is an advantage to using one over the other, assuming that you will not pass any parameters using the function. I feel that there may be a small overhead because the anonymous function will be called, but she would like a more informed opinion.

+4
source share
2 answers

Remember that in JavaScript, objects are passed by reference, so if you include the object as the default, it will be used for all instances. The default values ​​containing the objects passed by reference must be determined using the function if you do not want to exchange objects between all instances

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

Pretty much sums it up. The function method is recommended only if there are attributes of the object.

+5
source

I think there are no performance differences between the two methods you described. The default resolution method (= the called function or only the returned object) is determined by this line in the underscore.js file:

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

As for the benefits. A regular object offers a static way of declaring model defaults. You declare them upon expansion, and that will not change. A function, on the other hand, gives you the ability to change the default default flies without re-creating the entire class by changing the object that the function should return.

+1
source

Source: https://habr.com/ru/post/1488260/


All Articles