什么是原型,$.扩展,并返回this"不得不这么做

What are prototype, $.extend, and "return this" have to do?

本文关键字:quot 不得不 返回 原型 扩展 什么 this      更新时间:2023-09-26

我正在做一个遗留项目,我对这个做什么感到困惑

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?
        }
    });
});

我有开发木偶应用程序的经验,但上面的代码仍然让我困惑。没有文档,做这件事的人已经离开了。

继承和调用父函数

首先,一些信息:

  • OOP概念介绍
  • 继承
  • javascript中的OOP
  • 与骨干的继承
BaseComponent.prototype.initialize.call(this, options);  // what is this man?
  • BaseComponent 是一个构造函数(理解javascript构造函数),它有主干的extend辅助函数。这个辅助函数包含了原型继承的一些复杂性。

  • BaseComponent.prototype 是父类包含函数和属性的原型。

  • BaseComponent.prototype.initialize 是父类(BaseComponent)的一个函数,我们通过为这个模块定义一个新的initialize来覆盖它。

类的函数包含在prototype属性中。通过在父类原型的函数上使用.call函数,我们可以在当前对象的上下文中调用该函数。

复制对象

this.widgetOptions = $.extend({}, options); // what is this man?

这是创建一个新对象,其中options的属性被复制。这是使用jQuery的extend和它做一个浅拷贝。

这是一个很好的模式,因为:
  1. 它确保this.widgetOptions是一个对象,
  2. 它是一个副本,所以你可以安全地修改属性,而不影响接收到的options对象(它可以被调用代码重用)。

链接函数调用

return this; // what is this man?

用于链式函数调用,如:

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

render函数内部,它是一个骨干标准。但是在初始化中,它没有意义,因为您从未真正手动调用初始化。

From the Backbone's doc:

一个好的约定是在渲染结束时返回它以启用链接调用。

默认视图render:

render: function() {
    return this;
},