使用了Backbone 也有了一段时间, 只是之前调用肯定的使用一套方案,调研完毕以后直接交给下面人用去了,因而也没有继续深刻 react
最近又看了reactjs,很羡慕继承,想整合到项目中,可是用reactjs目前还不现实,多但愿Backbone 也能拥有这样的特性,因而就查看Backbone中的继承究竟是怎么回事。 app
如下是Backbone 中的extend源码部分 ide
// Helper function to correctly set up the prototype chain for subclasses. // Similar to `goog.inherits`, but uses a hash of prototype properties and // class properties to be extended. var extend = function(protoProps, staticProps) { var parent = this; var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call the parent constructor. if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function(){ return parent.apply(this, arguments); }; } // Add static properties to the constructor function, if supplied. _.extend(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function and add the prototype properties. child.prototype = _.create(parent.prototype, protoProps); child.prototype.constructor = child; // Set a convenience property in case the parent's prototype is needed // later. child.__super__ = parent.prototype; return child; }; // Set up inheritance for the model, collection, router, view and history. Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
backbone 文档中这样写道 this
extendBackbone.View.extend(properties, [classProperties])
Get started with views by creating a custom view class. You'll want to override therender function, specify your declarative events, and perhaps the tagName,className, or id of the View's root element. prototype
var DocumentRow = Backbone.View.extend({ tagName: "li", className: "document-row", events: { "click .icon": "open", "click .button.edit": "openEditDialog", "click .button.delete": "destroy" }, initialize: function() { this.listenTo(this.model, "change", this.render); }, render: function() { ... } });
Properties like tagName, id, className, el, and events may also be defined as a function, if you want to wait to define them until runtime. code
因而写了很长时间 Backbone.View.extend, 很悲催,看了源码以后才知道 parent = this; 因而打开思惟 其实VIEW也能够这样写的var A = Backbone.View.extend({ name:'name', initialize:function(){console.log(this.addr) //this.render(); }, test:function(){ return this.name; }, render:function(){ var $div = $('<div id="test-bean"></div>'); console.log("render2"); $('body').append($div); } }) var b = A.extend({ addr:"wxi", initialize:function(){ A.prototype.initialize.call(this);console.log('b') this.render(); }, getAddr:function(){ return this.addr; }, render:function(){ A.prototype.render.call(this); console.log("render"); }, }); console.log(b.prototype) var bb = new b(); console.log(bb.test());
打开思惟,这样咱们就能够作不少不少~~ ,具备特性的VIEW封装... router
//题外 CSS -- hack 继承