compose.js主要用于實現集成的一個javascript庫
這是相等的Javascript原生代碼
Widget = function(){ }; Widget.PRototype = { render: function(node){ node.innerHTML = "hi"; } } var widget = new Widget(); widget.render(node);相等的javascript語法
HelloWidget = function(){ this.message = "Hello, World"; }; HelloWidget.prototype = new Widget(); HelloWidget.prototype.render: function(){ this.node.innerHTML = "" + this.message + ""; }; var widget = new HelloWidget(); widget.render(node);相等的javascript
Widget = function(node){ this.node = node; }; Widget.prototype = { render: function(){ this.node.innerHTML = "hi"; }, getNode: function(){ return this.node; } } var widget = new Widget(node); widget.render();Compose can compose constructors from multiple base constructors, effectively providing multiple inheritance. For example, we could create a new widget from Widget and Templated base constructors:
TemplatedWidget = Compose(Widget, Templated, { // additional functionality });Again, latter argument’s methods override former argument’s methods. In this case, Templated’s methods will override any Widget’s method of the same name. However, Compose is carefully designed to avoid any confusing conflict resolution in ambiguous cases. Automatic overriding will only apply when later arguments have their own methods. If a later argument constructor or object inherits a method, this will not automatically override former base constructor’s methods unless it has already overriden this method in another base constructor’s hierarchy. In such cases, the appropriate method must be designated in the final object or else it will remain in a conflicted state. This essentially means that explicit ordering provides straightforward, easy to use, method overriding, without ambiguous magical conflict resolution (C3MRO).
這個技巧可以用來實現一個私有方法
var required = Compose.required; Widget = Compose(Widget, function(innerHTML){ // this will mixin the provide methods into |this| Compose.call(this, { generateHTML: function(){ return "" + generateInner() + ""; } }); // private function function generateInner(){ return innerHTML; } });create是立即建立一個對象.
一個快捷的建立子類的方法
MyClass = Compose(...); SubClass = MyClass.extend({ subMethod: function(){} }); // same as: SubClass = Compose(MyClass,{ subMethod: function(){} });新聞熱點
疑難解答