The first block of code defines a constructor function, which is called every time you new
up a view. In that function you can create public properties with the syntax:
this.foo = "bar";
This initialization code runs every time a view is initialized, and it attaches the properties to the instance of the view. Instance properties are not shared.
The second block of code extends the constructor function's prototype, first with all the properties of Backbone.View
, and then with the properties defined in the block. Prototype properties are shared between all instances of the function, or "class", if you wish.
What that code essentially does is create a new function, and then enhance it with Backbone.View
's properties. Because the Backbone.View
's own constructor function is never called (at least in the code you posted), it means that this class wouldn't quite work like a normal Backbone View. For instance a model
or id
property passed to a constructor would not be copied to the instance automatically, as they normally would:
var view = new av.Application.BaseView({model:model});
console.log(view.model); //-> undefined
Backbone also supports overriding the constructor function more cleanly by setting a constructor
attribute in the class definition:
av.Application.BaseView = Backbone.View.extend({
//override the constructor function
constructor: function(options) {
//this property is not shared between instances
this.foo = 'bar';
//call Backbone's own constructor, so we get all the default behavior
Backbone.View.prototype.constructor.apply(this, arguments);
},
//this property is attached to the prototype, and is shared
baz: 'qux'
});