js设计模式--链式调用
来源:互联网 发布:音乐间谍类似软件 编辑:程序博客网 时间:2024/05/16 05:24
<!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
阅读全文
0 0
- js设计模式--链式调用
- 【js设计模式笔记---方法的链式调用】
- 【js设计模式笔记---方法的链式调用】
- JavaScirpt设计模式——链式调用
- JavaScript设计模式 Item 5 --链式调用
- JavaScript设计模式 --- 方法的链式调用
- JavaScript设计模式:方法的链式调用
- JS dom树链式设计模式
- JS 链式调用
- js的链式调用
- JS链式调用
- js的链式调用
- js方法链式调用
- js链式调用
- js链式调用
- Builer模式链式调用
- javascript设计模式_第二部分_链式调用
- js链式调用的原理
- FTPrep: 54 Spiral Matrix.
- 华为迷宫问题 广度优先遍历 BFS
- 使用 eclipse 和 插件 开发 Kotlin
- Github的入门常识
- java中File类的getPath(),getAbsolutePath(),getCanonicalPath()区别
- js设计模式--链式调用
- minimum subtree
- 【ERROR 1366 (HY000): Incorrect string value】(关键词:字符集/character set)
- <c语言经典100例>c3 完全平方数
- linux使用ultraedit的FTP的功能出现的不能初始化的问题
- junit 4.12 学习笔记
- Git上传项目至远程仓库与同步到本地
- NYOJ 599 奋斗的小蜗牛
- 文章标题