++本文系慕課網(wǎng)學(xué)習(xí)筆記++
說(shuō)一下原型的實(shí)際應(yīng)用
解答思路:
- 描述一下 jQuery 如何使用原型
- 描述一下 zepto 如何使用原型
- 再結(jié)合自己的項(xiàng)目經(jīng)驗(yàn),說(shuō)一個(gè)自己開發(fā)的例子
jQuery 和 zepto 的簡(jiǎn)單使用
<p>jQuery test 1</p>
<p>jQuery test 2</p>
<p>jQuery test 3</p>
<div id="div1">
<p>jQuery test in div</p>
</div>
<script type="text/javascript" src="./jquery-3.2.1.js"></script>
<script type="text/javascript">
var $p = $('p')
$p.css('color', 'red') // css 是原型方法
console.log($p.html()) // html 是原型方法
var $div1 = $('div1')
$div1.css('color', 'blue') // css 是原型方法
console.log($div1.html()) // html 是原型方法
</script>
zepto 如何使用原型
// 空對(duì)象
(function (window) {
var zepto = {}
zepto.init = function(selector) {
// 源碼中這的處理情況比較復(fù)雜,但這里是針對(duì)原型所以就弱化了
var slice = Array.prototype.slice
var dom = slice.call(document.querySelectorAll(selector))
return zepto.Z(dom, selector)
}
// 即使用 zepto 時(shí)候的 $
var $ = function(selector) {
return zepto.init(selector)
}
window.$ = $
})(window)
// 構(gòu)造函數(shù)
function Z(dom, selector) {
var i, len = dom ? dom.length : 0
for (i = 0; i < len; i++) this[i] = dom[i]
this.length = len
this.selector = selector || ''
}
zepto.Z = function(dom, selector) {
// 注意出現(xiàn)了 new 關(guān)鍵字
return new Z(dom, selector)
}
$.fn = {
constructor: zepto.Z,
css: function (key, value) {
...
},
html: function(value) {
...
}
}
zepto.Z.prototype = Z.prototype =$.fn
jQuery 如何使用原型
var jQuery = function(selector) {
// new 關(guān)鍵字, 構(gòu)造函數(shù)
return new jQuery.fn.init(selector)
}
var init = jQuery.fn.init = function(selector) {
var slice = Array.prototype.slice
var dom = slice.call(document.querySelectorAll(selector))
var i, len = dom ? dom.length : 0
for (i = 0; i < len; i++) this[i] = dom[i]
this.length = len
this.selector = selector || ''
}
window.$ = jQuery
// 初始化 jQuery.fn
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
css: function (key, value) {
...
},
html: function(value) {
...
}
}
// 定義原型
init.prototype = jQuery.fn
原型如何實(shí)現(xiàn)它的擴(kuò)展性
解答思路:
- 說(shuō)一下 jQuery 和 zepto 的插件機(jī)制
- 結(jié)合自己的開發(fā)經(jīng)驗(yàn),做過(guò)的基于原型的插件
思考:為何要把原型方法放在 $fn?
// 因?yàn)橐獢U(kuò)展插件
$.fn.getNodeName = function() {
return this[0].nodeName
}
// 好處
// 只有 $ 會(huì)暴露在 window 全局變量
// 將插件擴(kuò)展統(tǒng)一到 $.fn.xxx 這一個(gè)接口,方便使用
總結(jié) zepto 和 jQuery 原型的使用
插件機(jī)制