学习Jquery的时候,我们通常会看到链式调用的写法
$(window).addEvent('load', function(){ $('test').show().setStyle('color', 'red').addEvent('click', function(e){ $(this).setStyle('color', 'yellow'); }); });
下面用JavaScript来实现一个链式调用,核心思想是借助原型构造函数,在每个方法中return this。
(function(){ function _$(els){ this.element = []; for(var i = 0, len = els.length; i < len; i++){ var element = els[i]; if(typeof element === 'string'){ element = document.getElementById(element); } this.element.push(element); } return this; } _$.prototype = { each: function(fn){ for(var i = 0, len = this.element.length; i < len; i++){ fn.call(this, this.element[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', 'none'); }); return this; }, addEvent: function(type, fn){ var add = function(el){ if(window.addEventListener){ el.addEventListener(type, fn, false); }else if(window.attachEvent){ el.attachEvent('on' + type, fn); } }; this.each(function(el){ add(el); }); } }; window.$ = function(){ return new _$(arguments); } })();
下面用JavaScript来实现一个链式调用,核心思想是给Number对象原型添加属性和方法。
(10).add(10).reduce(2).add(10) Number.prototype.add = function(num){ return this+num; } Number.prototype.reduce = function(num){ return this-num; }