1. 如何全局使用jQuery
2. 无new操作
3. init原型
4. 链式操作
一:封装作用域:
防止污染全局变量,可以使用命名空间或者闭包,jQuery采用闭包。
<div id="dom">Hello, I am Div.</div>
(function () {
window.jQuery = window.$ = jQuery; // 暴露jQuery函数给window
function jQuery(id) {
var dom = document.getElementById(id.slice(1));
this[0] = dom; // 0: div#dom
this.length = 1; // length: 1
return this; // 谁调用返回谁,window调用返回window,所以要new
}
})()
console.log( new $('#dom') ); // 谁调用返回谁,window调用返回window,所以要new
二:无new操作:
每次使用jQuery的时候都要new一下才能操作,为了不需要new,我们新建一个init()函数,在jQuery函数里面new init()函数。
(function () {
window.jQuery = window.$ = jQuery; // 暴露jQuery函数给window
function jQuery(id) {
return new init(id)
// 在jQuery()函数里return new init()函数实现无new操作
}
function init(id) {
var dom = document.getElementById(id.slice(1)); //
this[0] = dom; // 0: div#dom
this.length = 1; // length: 1
return this;
}
})()
console.log( $('#dom') ); // 实现无new调用
三:init原型:
init的原型是普通的Object,无法提供jQuery.prototype.下的方法,为了使用,我们把init.prototype = jQuery.prototype;
(function () {
window.jQuery = window.$ = jQuery; // 暴露jQuery函数给window
function jQuery(id) {
return new init(id)
// 在jQuery函数里return 一个init函数实现无new操作
}
function init(id) {
var dom = document.getElementById(id.slice(1));
this[0] = dom; // 0: div#dom
this.length = 1; // length: 1
return this;
}
jQuery.prototype.text = function() {
console.log('text');
}
jQuery.prototype.css = function() {
console.log('css');
}
// jQuery原型
init.prototype = jQuery.prototype;
// 因为init的原型是普通的object,无法提供方法
// 所以把init的原型指向jQuery原型
})()
console.log( $('#dom').text() ); // 返回text和undefined,
// 返回text是执行了text()方法中的console.log;
// 返回undefined是因为在最后console.log了text()方法的结果,return出来的是undefined,所以也是打印undefined
// 如果undefined再调用css()方法,那么将报错
四:链式调用:
为了能够连续正常调用$('#dom').css().text(),我们return this出去,谁调用返回谁。
(function () {
window.jQuery = window.$ = jQuery; // 暴露jQuery函数给window
function jQuery(id) {
return new init(id)
// 在jQuery函数里return 一个init函数实现无new操作
}
var init = jQuery.prototype.init = function(id) { // 定义在了闭包下和jQuery原型下
var dom = document.getElementById(id.slice(1));
this[0] = dom; // 0: div#dom
this.length = 1; // length: 1
return this;
}
jQuery.prototype.text = function() {
console.log('text');
return this;
}
jQuery.prototype.css = function() {
console.log('css');
return this; // 谁调用 返回谁
}
// jQuery原型
init.prototype = jQuery.prototype;
// 因为init的原型是普通的object,无法提供方法
// 所以把init的原型指向jQuery原型
})()
console.log ( $('#dom').css().text() ); // 返回css、text和init()函数
其他:init()函数定义在了闭包和jQuery原型下,所以var init = jQuery.prototype.init=functioninit(id) {}
本文介绍了jQuery的基本使用方法,包括如何全局使用、去除new操作、init原型的设置以及链式调用的实现。通过这些关键步骤,让开发者更好地理解和掌握jQuery的基础架构。
2万+

被折叠的 条评论
为什么被折叠?



