jQuery在JavaScript库中的一哥地位是不可撼动的,虽然随着这几年框架的崛起和一些大平台移除了jQuery的依赖,但不可否认jQuery还是前端开发必须掌握的技能。
jQuery的好处很多很多,其中链式调用是其中之一。网上很多说jQuery的链式调用是返回this对象,其实原理是这样的,只不过jQuery会更复杂。
jQuery自动缓存每一步的jQuery操作,返回的都是一个jQuery对象:
$('div').find('ul li').eq(2).html('第三个');
console.log($('div'));
console.log($('div').find('ul li'));
console.log( $('div').find('ul li').eq(2));
jQuery采用了缓存和返回jQuery对象,在效率上会比非链式的更高,在调用上也更简便。
我们可以实现最简单的this返回的链式调用:
function Fn() {
this.get = function () {
console.log('get');
return this;
}
this.post = function () {
console.log('post');
return this;
}
}
Fn.prototype.delete = function () {
console.log('delete');
return this;
}
var fn = new Fn();
fn.get().post().delete();这是构造函数和实例对象的链式调用,还有更简单的:
var fn = {
get: function () {
console.log('get');
return this;
},
post: function () {
console.log('post');
return this;
},
delete: function () {
console.log('delete');
return this;
}
}
fn.get().post().delete();方法函数可以这么去实现链式调用,至于jQuery怎么保存每一次的dom节点返回jQuery对象,暂时没有能力去研究。
(完)