What are prototype, $.extend, and “return this” ha

2019-09-15 01:18发布

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.

1条回答
趁早两清
2楼-- · 2019-09-15 02:16

Inheritance and calling parent functions

First, some informations:

BaseComponent.prototype.initialize.call(this, options);  // what is this man?
  • BaseComponent is a constructor function (understanding javascript constructors), which has the Backbone's extend 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 new initialize 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.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

return this; // 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() {
    return this;
},
查看更多
登录 后发表回答