往期回顾:jQuery的XX如何实现?——1.框架jQuery的XX如何实现?——2.show与链式调用jQuery的XX如何实现?——3.data与cache ...
往期回顾:
jQuery的XX如何实现?——1.框架
jQuery的XX如何实现?——2.show与链式调用
jQuery的XX如何实现?——3.data与cache机制
--------------------------
源码链接:内附实例代码
jQuery使用许久了,但是有一些API的实现实在想不通。于是抽空看了jQuery源码,现在把学习过程中发现的一些彩蛋介绍给大家(⊙0⊙)。
下面将使用简化的代码来介绍,主要关注jQuery的实现思想~>_<~
相较于第一篇(与第二、三篇无相关性),代码更新了:26~40
本章主要通过isFunction、isWindow、isNumberic三个的工具方法来学习类型检测和工具方法的定义。
1 (function(window, undefined){ 2 3 function jQuery(sel){ 4 return new jQuery.prototype.init(sel); 5 } 6 7 jQuery.prototype = { 8 constructor: jQuery, 9 init: function(sel){10 if(typeof sel === 'string'){11 var that = this;12 var nodeList = document.querySelectorAll(sel);13 Array.prototype.forEach.call(nodeList, function(val, i){14 that[i] = val;15 })16 this.selector = sel;17 this.length = nodeList.length;18 }19 }20 }21 22 jQuery.prototype.init.prototype = jQuery.prototype;23 24 window.$ = jQuery;25 26 jQuery.isFunction = function(obj) {27 return typeof obj === 'function';28 }29 30 //window.window 有点意思31 jQuery.isWindow = function(obj) {32 return obj && obj === obj.window;33 }34 35 jQuery.isNumberic = function(obj) {36 //return typeof obj === 'number';37 //return Object.prototype.toString.call(obj) === '[object Number]'; //发现情况一模一样38 //return !isNaN(obj) && isFinite(obj); //漏了null39 return !isNaN(parseFloat(obj)) && isFinite(obj);40 }41 42 })(window);
原标题:jQuery的XX如何实现?——4.类型检查
关键词:jquery
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。