我正在研究遗留项目,我对此做了什么感到困惑
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?
}
});
});
我有开发木偶应用程序的经验,但上面的代码仍然让我困惑。没有文档和执行此操作的人已离开。
答案 0 :(得分:2)
首先,一些信息:
BaseComponent.prototype.initialize.call(this, options); // what is this man?
BaseComponent
是构造函数(understanding javascript constructors),其中包含Backbone's extend
helper function。这个辅助函数包含了prototypal inheritance。
BaseComponent.prototype
是包含函数和属性的父类的原型。
BaseComponent.prototype.initialize
是父类(BaseComponent
)的函数,我们通过为此模块定义新的initialize
来覆盖它。
“class”的功能包含在prototype
property中。通过在父类原型的函数上使用.call
function,我们可以在当前对象的上下文中调用该函数。
this.widgetOptions = $.extend({}, options); // what is this man?
这是一个新对象,其中复制了options
的属性。这是使用jQuery's extend
并且它是一个浅表副本。
这是一个很好的模式,因为:
this.widgetOptions
是一个对象,options
对象(可以由调用代码重用)。return this; // what is this man?
这适用于chain function calls,如下所示:
myView.render().lookImChaining().functionCalls();
在render
功能中,它是一个Backbone标准。但是在初始化中,没有任何意义,因为你从未真正手动调用初始化。
一个好的约定是在渲染结束时将其返回以启用 链式电话。
render: function() { return this; },