如何使用下划线创建自己的可继承类

How to create own inheritable class with underscore

本文关键字:可继承 自己的 创建 何使用 下划线      更新时间:2023-09-26

我想构建一个类似Backbone.Model的对象/类。

我查看了Backbone文档,发现他们创建了一个具有可继承属性的可继承对象/类,方法分为两个步骤:

I。创建具有某些属性的函数

var Model = Backbone.Model = function(attributes, options) {
    var defaults;
    attributes || (attributes = {}); //?
    if (options && options.parse) attributes = this.parse(attributes); //?
    if (defaults = getValue(this, 'defaults')) {
      attributes = _.extend({}, defaults, attributes); // ?
    }
    if (options && options.collection) this.collection = options.collection;
    this.attributes = {};
    this._escapedAttributes = {};
    this.cid = _.uniqueId('c');
    this.changed = {};
    this._silent = {};
    this._pending = {};
    this.set(attributes, {silent: true});
    this.changed = {};
    this._silent = {};
    this._pending = {};
    this._previousAttributes = _.clone(this.attributes);
    this.initialize.apply(this, arguments);
};

II。使用下划线的扩展赋予它一些功能

_.extend(Model.prototype, Events, { // Events?
   changed: null,
   _silent: null,
   _pending: null,
   idAttribute: 'id',
   initialize: function(){},
   toJSON: function(options) {
       return _.clone(this.attributes);
   }
   // other Model methods...
};

我对这种行为有一些疑问:

  1. 第一部分第3-4行做什么
  2. 第6行发生了什么
  3. 为什么我们过度使用"_.extend"Events对象,我还能给出什么作为参数

还有什么需要我注意的吗?

问候

线路3,attributes || (attributes = {});是短路评估的一个示例。如果属性有一个错误的valye,那么javascript将计算OR表达式的第二部分。该部分为attributes指定一个值{},一个空对象。最终的结果是,如果属性为null或未定义(典型情况),则为属性分配一个空对象。

这句话相当于说:

if (attributes == false) { // attributes can be any value that evaluates to false
                           // attributes could be null, undefined, false, 0 etc
   attributes = {};
}

与线路4相同,if (options && options.parse) attributes = this.parse(attributes);

如果存在一个options对象,即它不是null或未定义,并且options对象具有一个名为parse的有效属性,则为属性分配值this.parse(attributes)

编辑1:

_.extend行可以通过Undercore.js文档进行解释。

这是创建一个新对象的标准模式,该对象将包含所有传入对象的属性。在第一个示例attributes = _.extend({}, defaults, attributes); // ?中,该模式用于用可能已经传递的内容覆盖默认值。您会在大多数允许传入选项对象的插件中看到这种模式。如果您没有传入任何内容,将使用默认值。如果只传入少数属性,其余属性将从默认值中获取值。

http://api.jquery.com/jQuery.extend/不是完全一样的东西。但它非常相似。他们的文档要好得多。你会更好地理解这个概念。

编辑2:

Backbone Events类具有一些与事件处理相关的方法。Backbone Model类还需要能够利用事件处理。它需要引发事件来告诉视图重新呈现自己,当视图更改底层数据时,它需要侦听来自dom的事件。该事件处理功能可以在定义Model类时从头开始重写,也可以扩展Model类以从Events类中获取这些方法。后一种情况正在发生。

如果您阅读$.extend或_.extend的文档,您会意识到Model类不仅使用Events下的属性进行了扩展,还使用了其他属性,如toJSON和initialize等。

关于第6行发生的事情-创建的对象包含defaults对象的所有属性和attributes对象的所有内容。attributes对象中已经定义的defaults对象的任何属性都将被后者的值覆盖。