<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>测试js设计模式--链式调用</title>
</head>
<body>
<div id="b1">测试js设计模式--链式调用</div>
<script>
(function(window , undefined){
// $ 最常用的对象 返回给外界 大型程序开发 一般使用'_'作为私用的对象(规范)
function _$(arguments){
//实现代码...这里仅实现ID选择器
// 正则表达式匹配id选择器
var idselector = /#\w+/ ;
this.dom ; // 此属性 接受所得到的元素
// 如果匹配成功 则接受dom元素 arguments[0] = '#inp'
if(idselector.test(arguments[0])){
this.dom = document.getElementById(arguments[0].substring(1));
} else {
throw new Error(' arguments is error !');
}
};
// 在_$的原型对象上 加一些公共的方法
_$.prototype = {
constructor : _$ ,
addEvent:function(type,fn){
// 给你的得到的元素 注册事件
if(window.addEventListener){// FF
this.dom.addEventListener(type , fn);
} else if (window.attachEvent){// IE
this.dom.attachEvent('on'+type , fn);
}
return this ;
},
setStyle:function(prop , val){
this.dom.style[prop] = val ;
return this ;
}
};
// 写一个准备的方法
_$.onReady = function(fn){
// 1 实例化出来_$对象 真正的注册到window上
window.$2 = function(){
return new _$(arguments);
};
// 2 执行传入进来的代码
fn();
};
// window 上先注册一个全局变量 与外界产生关系
window.$2 = _$ ;
})(window);
$2.onReady(function(){
var inp = $2('#b1');
inp.addEvent('click',function(){
alert('我被点击了!');
}).setStyle('color' , 'red');
});
</script>
</body>
</html>
使用回调函数从支持链式调用的方法获取数据
链式调用很适合于赋值器方法,但对于取值器方法,就不方便了,因为每个方法返回的都是this啊。
不过,变通的方法还是有的,那就是回调函数。
window.API2 = window.API2 || function(){
var name = 'JChen';
this.setName = function(newName){
name = newName;
return this;
};
this.getName = function(callback){
callback.call(this, name);
return this;
};
};
var o2 = new API2();
var log = function(para){
console.log(para);
};
o2.getName(log).setName('Hehe').getName(log);
输出结果:
JChen
Hehe