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(){} });新闻热点
疑难解答