When should defaults be a function?

I started by looking at the application localtodosand see that this code makes it a function. I do not know how to make this choice. My assumption is that the code in the function is not executed until you call a function other than the object literal and which will be interpreted immediately.

Here is a usage example:

var FavoritesRow = Backbone.Model.extend({
    Name: 'FavoritesRow',
    defaults: function () {
        return {
            url: "http://www.google.com",
            title: "google",
            favicon: "http://www.google.com/favicon.ico",
            tag: "search"
        };
    }
});

But which rule / rules should be followed in general?

+1
source share
2 answers

From the exact guide tomodel.defaults :

, JavaScript , , . .

var M = Backbone.Model.extend({
    defaults: {
        obj: {}
    }
});

var m1 = new M();
var m2 = new M();
console.log(m1.get('obj') === m2.get('obj'));
// ==> outputs true

http://jsfiddle.net/nikoshr/6ctZ2/

var M = Backbone.Model.extend({
    defaults: function() {
        return {
            obj: {}
        };
    }
});

var m1 = new M();
var m2 = new M();
console.log(m1.get('obj') === m2.get('obj'));
// ==> outputs false

http://jsfiddle.net/nikoshr/6ctZ2/1/

.

+4

, :

a) this
) c) ( )

, , initialize, :

this.defaults = {} // Now it is instance-scope

, _.result this. , . if (_.isFunction(this.x)) this.x.call(this). defaults _.result , , .

0

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


All Articles