Welcome

首页 / 脚本样式 / jQuery / jQuery链式操作的问题

jQuery链式操作的问题2013-10-18 cnblogs Justany_WhiteSnow两个问题

1.jQuery的链式操作是如何实现的?

2.为什么要用链式操作?

大家认为这两个问题哪个好回答一点呢?

链式操作

原理相信百度一下一大把,实际上链式操作仅仅是通过对象上的方法最后

return this

把对象再返回回来,对象当然可以继续调用方法啦,所以就可以链式操作了。那么,简单实现一个:

//定义一个JS类function Demo() {}//扩展它的prototypeDemo.prototype ={setName:function (name) {this.name = name;return this;},getName:function () {return this.name;},setAge:function (age) {this.age = age;return this;}};////工厂函数function D() {return new Demo();}//去实现可链式的调用D().setName("CJ").setAge(18).setName();
但……为什么要用呢?

一般的解释:

节省代码量,代码看起来更优雅。

例如如果没有链式,那么你可能需要这样写代码:

document.getElementById("ele").dosomething();
document.getElementById("ele").dootherthing();

这个代码中调用了两次document.getElementById来获取DOM树的元素,这样消耗比较大,而且要写两行,而链式只要写一行,节省了代码……

但我们也可以用缓存元素啊。比如:

var ele = document.getElementById("ele");ele.dosomething();ele.dootherthing();