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();
这边简单实现一下通过ID的$
function Fn(elId) {
this.el = document.getElementById(elId);
return this
}
Fn.prototype.css = function (prop, val) {
this.el.style[prop] = val;
return this
}
Fn.prototype.hidden = function () {
this.css('display', 'none');
return this
}
Fn.prototype.show = function () {
this.css('display', 'block');
return this
}
window.$ = function (el) {
return new Fn(el)
}
$('test').css('width', '300px').css('height', '300px').css('background', 'red').hidden().show()
本来我们通过var fn = new Fn(‘test’);就能链式调用,但是我们不同ID不可能一直无创建实例对象,所以才有了
window.$ = function (el) {
return new Fn(el)
}
方法函数可以这么去实现链式调用,jQuery大概的实现思路差不多也是这样,当然,jQuery实现起来是非常复杂的,需要保存每一次的dom节点返回jQuery对象,兼容各种场景等,暂时没有能力去解析源码。