Skip to content Skip to sidebar Skip to footer

What Are Prototype, $.extend, And "return This" Have To Do?

I'm working on a legacy project, I'm confused with what this does define(['jquery', 'components/BaseComponent', 'bootstrap'], function( $, BaseComponent, bootstrap ) { 'use

Solution 1:

Inheritance and calling parent functions

First, some informations:

BaseComponent.prototype.initialize.call(this, options);  // what is this man?

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.widgetOptions = $.extend({}, options); // what is this man?

This is making a new object, in which properties of options are copied over. This is using jQuery's extend and it makes a shallow copy.

This is a good pattern because:

  1. it ensures that this.widgetOptions is an object,
  2. it's a copy so you can safely modify the properties without affecting the received options object (which could be reused by the calling code).

Chaining function calls

returnthis; // what is this man?

This serves to chain function calls, like this:

myView.render().lookImChaining().functionCalls();

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:

A good convention is to return this at the end of render to enable chained calls.

The default view render:

render: function() {
    returnthis;
},

Post a Comment for "What Are Prototype, $.extend, And "return This" Have To Do?"