码迷,mamicode.com
首页 > Web开发 > 详细

JS 链式调用

时间:2015-04-15 23:04:20      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

  

<!-- ————————JS函数链式调用——————— -->
function Dog(){
this.run=function(){
alert("跑");
return this;
};
this.eat=function(){
alert("吃");
return this;
};
this.sleep=function(){
alert("睡觉");
return this;
};
}
var dog=new Dog();
dog.run().eat().sleep();

 

 

<!-- ————————JS函数链式调用(模拟jquery链式调用)——————— -->
//jquery底层使用块级作用域
//块级作用域特点: 程序启动代码执行 内部成员变量 外部无法访问
(function(window,undefined){
//$符号返回给外部 大型程序一般使用‘_‘作为私有对象
function _$(arguments){

 

}
//在Function上扩展一个可以实现链式编程的方法
Function.prototype.method=function(methodName,fun){
this.prototype[methodName]=fn;
return this;
}
//在_$的原型对象上加方法
_$.prototype={
constructor:_$,
addEvent:function(){
alert("addEvent");
return this;
},
setStyle:function(){
alert("setStyle");
return this;
}
}
//在window上注册一个全局变量 与外界产生联系
window.$=_$;
//实现一个准备方法
_$.onReady=function(fn){
//1.实例化_$对象 真正的注册到window上
window.$=function(){
return new _$(arguments);
}
//2.执行传入的代码
fn();
//3.实现链式编程
_$.method(‘addEvent‘,function(){}).method(‘setStyle‘,function(){});
}
})(window);//程序入口 传入window到块级作用域中

$.onReady(function(){
$("#").addEvent().setStyle();
});

 

JS 链式调用

标签:

原文地址:http://www.cnblogs.com/jalja/p/4430259.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!