Today I was playing around with Backbone and Javascript, and came upon an interesting problem. Consider the following:
var App = {};
App.model = Backbone.Model.Extend({/* Omitted for brevity */});
App.view = Backbone.View.Extend({/* Omitted for brevity */});
App.obj = new App.view();
At this point I wanted to refactor for readability and mantainability's sake:
var App = {
model: Backbone.Model.Extend({}),
view: Backbone.View.Extend({}),
obj: new view() // Here comes trouble
}
The snippet above is what I wanted to obtain, but obviously the initialization doesn't work:
view
is not in scopeApp
is not yet initialized, soApp.view
isn't usable.this
refers towindow
, sothis.view
isn't usable.
At this point, with the help of this answer I concocted a solution:
var App = {
model: Backbone.Model.Extend({}),
view: Backbone.View.Extend({}),
get obj() { delete this.obj; this.obj = new this.view(); return this.view; }
}
Using the getter I'm able to delay the creation of the object instance until used (thus after completing App initialization), and then I replace the getter from within with the object instance.
Everything works as expected, but since I'm not exactly fluent with modern JS I was wondering if there was a different or proper way to achieve what I wanted. I was also wondering if this sort of implementation could cause drawbacks or unexpected problems I'm not considering.