Nikel Weis
Nikel Weis

Reputation: 724

What is the difference between those two model definitions?

I'm new to backbone.js and I've a question regarding model definitions. In various tutorials and introductions I've seen those three approaches in defining a model:

Tour = Backbone.Model.extend({

    idAttribute: 'id',

    urlRoot: '/api/tour',

});

return Tour;
});

And the other next one:

**var** Tour = Backbone.Model.extend({

    idAttribute: 'id',

    urlRoot: '/api/tour',

});

return Tour;
});

I've also seen this one:

Tour = Backbone.Model.extend({

    idAttribute: 'id',

    urlRoot: '/api/tour',

});

return **new Tour()**;
});

I've read that the first one is in "the global namespace" which had in fact no effect for me in programming. So where is the difference between those three (especially first and second one) and when shall which be used?

Upvotes: 0

Views: 31

Answers (1)

Rida BENHAMMANE
Rida BENHAMMANE

Reputation: 4129

1- In the first approach you are creating a global variable named Tour so wherever you are Tour will point to your model class.

2- In the second one you are creating a local variable pointing to your model class and returning it, so whenever you want want to use your model you have to instantiate the returned variable and that's it.

3- In the third approach you are creating your model class, instantiating it and returning the instance, so all your program will share the same instance !!

The correct approach is the second one, because in the first the use of global vars in javascript is discouraged and the the third approach is not working.

Upvotes: 2

Related Questions