zepto的简单实现
(function (window) { var zepto = {} 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) { return new Z(dom, selector) } zepto.init = function (selector) { var slice = Array.prototype.slice var dom = slice.call(document.querySelectorAll(selector)) return zepto.Z(dom, selector) } var $ = function (selector) { return zepto.init(selector) } window.$ = $ $.fn = { css: function (key, value) { alert('css') }, html: function (value) { return '这是一个模拟的 html 函数' } } Z.prototype = $.fn })(window)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <p>zepto test 1</p> <p>zepto test 2</p> <p>zepto test 3</p> <div id="div1"> <p>zepto test in div</p> </div> <script type="text/javascript" src="./my-zepto.js"></script> <script type="text/javascript"> var $p = $('p') $p.css('font-size', '40px') alert($p.html()) var $div1 = $('#div1') $div1.css('color', 'blue') alert($div1.html()) </script> </body> </html>
jQuery的简单实现
(function (window) { var jQuery = function (selector) { return new jQuery.fn.init(selector) } jQuery.fn = { css: function (key, value) { alert('css') }, html: function (value) { return 'html' } } 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 || '' } init.prototype = jQuery.fn window.$ = jQuery })(window)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <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="./my-jquery.js"></script> <script type="text/javascript"> var $p = $('p') $p.css('font-size', '40px') alert($p.html()) var $div1 = $('#div1') $div1.css('color', 'blue') alert($div1.html()) </script> </body> </html>
为什么会把原挂载到$.fn上或者jQuery.fn上?
只有 $ 会暴露在 window 全局变量
将插件扩展统一到 $.fn.xxx 这一个接口,方便使用
例如$.fn.add=function(x,y){return x+y}
2019-05-09 17:45:04