I'm working on a legacy project, I'm confused with what this does
define(['jquery', 'components/BaseComponent', 'bootstrap'], function(
$, BaseComponent, bootstrap
) {
'use strict';
return BaseComponent.extend({
initialize: function(options) {
BaseComponent.prototype.initialize.call(this, options); // what is this man?
this.widgetOptions = $.extend({}, options); // what is this man?
return this; // what is this man?
},
render: function() {
BaseComponent.prototype.render.call(this); //again?
return this; //again?
}
});
});
I have experience developing marionette app but above code still confused me. No documentation and the one who did this has left.
Inheritance and calling parent functions
First, some informations:
BaseComponent
is a constructor function (understanding javascript constructors), which has the Backbone'sextend
helper function. This helper function wraps some of the complexity of prototypal inheritance.BaseComponent.prototype
is the prototype of the parent class containing functions and properties.BaseComponent.prototype.initialize
is a function of the parent class (BaseComponent
), which we are overriding by defining a newinitialize
for this module.Functions of a "class" are contained inside the
prototype
property. By using the.call
function on a function from the parent's prototype, we can call the function in the context of the current object.Making copy of objects
This is making a new object, in which properties of
options
are copied over. This is using jQuery'sextend
and it makes a shallow copy.This is a good pattern because:
this.widgetOptions
is an object,options
object (which could be reused by the calling code).Chaining function calls
This serves to chain function calls, like this:
Inside the
render
function, it is a Backbone standard. But in the initialize, it makes no sense since you never actually call the initialize manually.From the Backbone's doc:
The default view
render
: