链式调用的方法获取数据
使用回调函数从支持链式调用的方法获取数据。链式调用很适合赋值器方法,但对于取值器方法,你可能希望他们返回你要的数据而不是 this(调用该方法的对象). 解决方案:利用回调技术返回所要的数据.
- window.API = window.API || function() {
- var name = 'mackxu';
- //特权方法
- this.setName = function(name0) {
- name = name0;
- return this;
- };
- this.getName = function(callback) {
- callback.call(this, name);
- return this;
- };
- };
- //------------- test ---
- var obj = new API();
- obj.getName(console.log).setName('zhangsan').getName(console.log);
设计一个支持方法链式调用的 JS 库
JS 库特征:
事件: 添加和删除事件监听器、对事件对象进行规划化处理
DOM: 类名管理、样式管理
Ajax: 对 XMLHttpRequest 进行规范化处理
- Function.prototype.method = function(name, fn) { this.prototype[name] = fn;
- return this;
- }; (function() {
- function _$(els) { //...
- }
- /*
- * Events
- * addEvent
- * removeEvent
- */
- _$.method('addEvent',
- function(type, fn) { //...
- }).method('removeEvent',
- function(type, fn) {
- })
- /*
- * DOM
- * addClass
- * removeClass
- * hover
- * hasClass
- * getClass
- * getStyle
- * setStyle
- */
- .method('addClass',
- function(classname) { //...
- }).method('removeClass',
- function(classname) { //...
- }).method('hover',
- function(newclass, oldclass) { //...
- }).method('hasClass',
- function(classname) { //...
- }).method('getClass',
- function(classname) { //...
- }).method('getStyle',
- function(prop) { //...
- }).method('setStyle',
- function(prop, val) { //...
- })
- /*
- * AJAX
- * ajax
- */
- .method('ajax',
- function(url, method) { //...
- }); window.$ = function() {
- return new _$(arguments);
- }; //解决JS库命名冲突问题
- window.installHelper = function(scope, interface) { scope[interface] = function() {
- return _$(arguments)
- }
- }
- })();
小结:
链式调用有助于简化代码的编写工作,并在某种程度上可以让代码更加简洁、易读。很多时候使用链式调用可以避免多次重复使用一个对象变量,从而减少代码量。如果想让类的接口保持一致,让赋值器和取值器都支持链式调用,那么你可以在取值器中使用回调函数来解决获取数据问题。
来源: