分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

看jquery3.3.1学js类型判断的技巧

发布时间:2023-09-06 01:49责任编辑:白小东关键词:js

需要预习:call , typeof, js数据类型

1. isFunction中typeof的不靠谱

源码:

var isFunction = function isFunction( obj ) {// Support: Chrome <=57, Firefox <=52// In some browsers, typeof returns "function" for HTML <object> elements// (i.e., `typeof document.createElement( "object" ) === "function"`).// We don‘t want to classify *any* DOM node as a function. ?return typeof obj === "function" && typeof obj.nodeType !== "number";};

typeof 是为了区分数据类型,下面是MDN中总结的typeof中所有存在的值

问题一:我们都知道typeof null 出来的结果是‘object’,可这是为啥呢?MDN给出了答案 :因为null是空指针,而空指针在大多数平台中使用0x00表示,而js在实现初期通过用 0 作为对象的标签,所以对null也被判断为object。

问题二:既然typeof能够判断出function,为何jquery额外判断   typeof obj.nodeType !== "number" 呢?

            long long ago,在那些古老的浏览器中:

            1. typeof document.body.childNodes  // function   这在古老的 safari 3 中会出现

            2.typeof document.createElement("object")  // function 同理还有 ‘embed‘  ‘applet‘ ,  在古老的firefox中会出现,目前新版本不会存在

            3.typeof /s/ // function  这种情况会在古老浏览器中出现,目前都会被判定为 object

 通过以上问题我们可以看出,通过typeof判断数据类型在古老的浏览器中是极为不靠谱的,所以在jquery的isFunction的判断中额外添加了判断 检测对象是否为dom 对象

2.靠谱的数据类型判断 

源码:

var class2type = {};var toString = class2type.toString;// Populate the class2type map,这里并没有undefinedjQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),function( i, name ) { ???class2type[ "[object " + name + "]" ] = name.toLowerCase();} );function toType( obj ) { ???if ( obj == null ) { ???????return obj + ""; ???} ???// Support: Android <=2.3 only (functionish RegExp) ???return typeof obj === "object" || typeof obj === "function" ? ???????class2type[ toString.call( obj ) ] || "object" : ???????typeof obj;}

在代码中jquery做了这几件事:

1.jquery先提取出toString 这个方法

2.将写好的类型字符串分割并存入class2type中,class2type 数据结构如下:

3.定义toType方法,因为 toString(null)会得出‘ [object Undefined]’的结果,所以需要把null单独判断,注意null是没有toString这个方法的,所以通过 obj+‘‘这个方式得到 ‘null‘

4.在单独判断null后是一个三元运算符:等价于

1 if(typeof obj === "object" || typeof obj === "function"){2 ????// 因为上文提到存在typeof /s/ 为 function的情况,所以需要toString详细判断3 ???// 对于判断不出的数据类型默认为object4 ????retrun class2type[ toString.call( obj ) ] || "object";5 } else {6 ????// 通过上面typeof对类型判断的表格,判断非object function还是很可靠的,所以直接用原生方法7 ????return typeof obj;8 }

结论: 通过用toString方法可以判断出Boolean、Number、 String、 Function、 Array、 Date、 RegExp、 Object、 Error、 Symbol、undefined 这些数据类型,但是并不能判断出null,所以要综合判断,就酱

看jquery3.3.1学js类型判断的技巧

原文地址:https://www.cnblogs.com/JhoneLee/p/8856567.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved