backbone和underscore中的extend

老是把這兩個庫中的extend搞混了因此寫下來。app

backbone中的extend實現了繼承:ide

 1   // Helper function to correctly set up the prototype chain for subclasses.
 2   // Similar to `goog.inherits`, but uses a hash of prototype properties and
 3   // class properties to be extended.
 4   var extend = function(protoProps, staticProps) {
 5     var parent = this;
 6     var child;
 7 
 8     // The constructor function for the new subclass is either defined by you
 9     // (the "constructor" property in your `extend` definition), or defaulted
10     // by us to simply call the parent constructor.
11     if (protoProps && _.has(protoProps, 'constructor')) {
12       child = protoProps.constructor;
13     } else {
14       child = function(){ return parent.apply(this, arguments); };
15     }
16 
17     // Add static properties to the constructor function, if supplied.
18     _.extend(child, parent, staticProps);
19 
20     // Set the prototype chain to inherit from `parent`, without calling
21     // `parent`'s constructor function and add the prototype properties.
22     child.prototype = _.create(parent.prototype, protoProps);
23     child.prototype.constructor = child;
24 
25     // Set a convenience property in case the parent's prototype is needed
26     // later.
27     child.__super__ = parent.prototype;
28 
29     return child;
30   };
31 
32   // Set up inheritance for the model, collection, router, view and history.
33   Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
View Code

underscore中的extend實現了屬性的複製,這是淺複製:函數

 1 _.extend = createAssigner(_.allKeys);
 2 
 3 var createAssigner = function(keysFunc, undefinedOnly) {
 4     return function(obj) {
 5       var length = arguments.length;
 6       if (length < 2 || obj == null) return obj;
 7       for (var index = 1; index < length; index++) {
 8         var source = arguments[index],
 9             keys = keysFunc(source),
10             l = keys.length;
11         for (var i = 0; i < l; i++) {
12           var key = keys[i];
13           if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
14         }
15       }
16       return obj;
17     };
18   };
View Code

 仔細閱讀後,backbone中的extend分爲4個步驟完成繼承:this

(1)定義一個子類(返回的對象)spa

(2)給子類賦值一個function,方法題中調用call方法prototype

(3)將父類的靜態屬性擴展後(擴展的屬性就是函數參數)賦值給子類code

(4)將父類的原型擴展(擴展的屬性就是該函數的參數)後賦值給子類的原型router

這種寫法有一點很差,就是徹底沒有私有變量和私有方法,只能依靠人爲的約束對象

相關文章
相關標籤/搜索