在javascript中,方法的链式调用很流行,使用jQuery的朋友对此一定深有体会。在《javascript设计模式》中对这种方法作了比较详细的描述,实现方法的链式调用,只须让在原型中定义的方法都返回调用这些方法的实例对象的引用即可,看看书中的这段代码:
(function() { function _$(els) { this.elements = []; for (var i = 0, len = els.length; i < len; ++i) { var element = els[i]; if (typeof element == ''string'') { element = document.getElementById(element); } this.elements.push(element); } }; _$.prototype = { each: function(fn) { for ( var i = 0, len = this.elements.length; i < len; ++i ) { fn.call(this, this.elements[i]); } return this; }, setStyle: function(prop, val) { this.each(function(el) { el.style[prop] = val; }); return this; }, show: function() { var that = this; this.each(function(el) { that.setStyle(''display'', ''block''); }); return this; }, addEvent: function(type, fn) { var add = function(el) { if (window.addEventListener) { el.addEventListener(type, fn, false); } else if (window.attachEvent) { &n |