读书人

怎么设计一个支持方法链式调用的JavaS

发布时间: 2012-11-25 11:44:31 作者: rapoo

如何设计一个支持方法链式调用的JavaScript库

废话不多说,代码摆出来,注释什么的都很清楚,如果看不很懂,请移步?javascript链式调用

?

//设计一个支持方法链式调用的JavaScript库

/*常见于大多数JavaScript库中的特性—————————————————————————————————————————————————————————————————————特性|说明————————————————————————————————————————————————————————————————————————————————事件|添加和删除事件监听器,对时间对象进行规范内化处理DOM|类名管理,样式管理Ajax|多XMLHttpRequest进行规范化处理————————————————————————————————————————————————————————————————————————————————注:可以对私有的_$构造函数进行扩充*/Function.prototype.method = function(name, fn){this.prototype[name] = fn;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;}/*Events* addEvent*/_$.method('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);});})./*otherFun* each* setStyle* show*/method('otherFun', function(fn){for(var i = 0, len = this.element.length; i < len; i++){fn.call(this, this.element[i]);}return this;}).method('setStyle', function(prop, val){this.each(function(el){el.style[prop] = val;});return this;}).method('show', function(){var that = this;this.each(function(el){that.setStyle('display', 'none');});return this;});window.installHelper = function(scope, interface){scope[interface] = function(){return new _$(arguments);};};})();/*//处理库中$的冲突问题用户可能会这样使用:installHelper(window, "$");$('example').show();也可以将功能添加到实现定义好的命名空间对象中:window.com = window.com || {};com.example = com.example || {};com.example.util = com.example.util || {};installHelper(com.example.util, '$');(function(){var get = com.example.util.get;get('example').show();})();*/
1 楼 mfkvfn 2012-09-18 不就是settter方法最后return this;么?说得那么高深干嘛

读书人网 >JavaScript

热点推荐