判断js中各种数据的类型方法之typeof与0bject.prototype.toString讲解
提醒大家,Object.prototype.toString().call(param)返回的[object class]中class首字母是大写,像JSON这种甚至都是大写,所以,大家判断的时候可以都转换成小写,以防出错
1、typeof(param) 返回param的类型(string)
这种方法是JS中的定义的全局方法,也是编译者们最常用的方法,优点就是使用简单、好记,缺点是不能很好的判断object、null、array、regexp和自定义对象。
示例代码:
var arr=['1','2'];
var num=1;
var bool=true;
var obj={name:'test'};
var nullObj=null;
var undefinedObj=undefined;
var reg=/reg/;
function fn(){
alert('this is a function');
}
function User(name){
this.name=name;
}
var user=new User('user');
console.log(typeof(str));
console.log(typeof(arr));
console.log(typeof(num));
console.log(typeof(bool));
console.log(typeof(obj));
console.log(typeof(nullObj));
console.log(typeof(undefinedObj));
console.log(typeof(reg));
console.log(typeof(fn));
console.log(typeof(user));
结果为:
object
number
boolean
object
object
undefined
object
function
object
2、Object.prototype.toString().call(param) 返回param的类型(string,格式是[object class])
这个方法能支持绝大多数类型的判断,jquery封装的类型判断就用的这个方法。可能有些人看起来有点迷茫,我来给大家分解一下。
1)call(param)函数
a.fun().call(b)的意思在js中是指,让对象b来代替a,然后执行a的fun函数,写个例子:
{
this.name = "class1";
this.showNam = function()
{
alert(this.name);
}
}
function Class2()
{
this.name = "class2";
}
var c1 = new Class1();
var c2 = new Class2();
c1.showNam.call(c2);
运行结果,输出的为class2,而不是class1,这就相当于是方法继承。
所以,Object.prototype.toString().call(param)的意思其实就是,param.prototype.toString(),那么我们为什么不直接写param.prototype.toString(),而是用call()绕一下呢,下面请看2来了解。
2)Object.prototype.toString()
Object是个什么东东呢?,Script56.chm(就是M$官方教程)上说:Obect提供所有 JScript对象通用的功能,其实Object就是所有js对象的祖先,是一个概念,js中的所有对象就是Object的实例,然后不同的对象重写自己独立的方法。而prototype,大家就没必要追究太深了,它就是返回一个原型的引用,然可以可以动态的给原型添加方法和属性
一个小例子
this.name = "class";
this.showName = function(){
alert(this.name);
}
}
var obj = new class();
obj.showName();
class.prototype.showNameContact = function(){
alert("prototype test"+this.name);
}
obj.showNameContact();
那么就会分别输出 class和prototype test class,本来构造函数class() 里是没有定义showNameContact函数的,而通过prototype我们就可以给对象原型动态添加函数,new的示例中自然就会有了。所以Object.prototype.toString()的意思就是执行Object这个祖先中的toString方法。
那么toString()是干嘛的呢?很多js手册中对toString()函数是这样定义的:
toString() 方法可把一个逻辑值转换为字符串,并返回结果,语法为:booleanObject.toString()。刚才我说了,js中的对象都是继承的Object,这些对象都自定义的有函数或者重构了Object的部分函数,而且它们都对toString()函数进行了重写。所以我们不能想1中直接写param.prototype.toString()这样就执行的是param自己重写后的toString()函数了。
好了,到关键的时刻了,toString()到底是干嘛的呢,有什么作用呢?
在ES3中,Object.prototype.toString方法的规范如下:
Object.prototype.toString()
在toString方法被调用时,会执行下面的操作步骤:
1. 获取this对象的[[Class]]属性的值.
2. 计算出三个字符串"[object ", 第一步的操作结果Result(1), 以及 "]"连接后的新字符串.
3. 返回第二步的操作结果Result(2).
在ES3中,规范文档并没有总结出[[class]]内部属性一共有几种,不过我们可以自己统计一下,原生对象的[[class]]内部属性的值一共有10种.分别是:"Array", "Boolean", "Date", "Error", "Function", "Math", "Number", "Object","RegExp", "String".所以Object.prototype.toString()的输出结果就是这种格式的字符串[object Array],[object Boolean]。
在ES5.1中,除了规范写的更详细一些以外,Object.prototype.toString方法和[[class]]内部属性的定义上也有一些变化,Object.prototype.toString方法的规范如下:
Object.prototype.toString ( )
在toString方法被调用时,会执行下面的操作步骤:
1 如果this的值为undefined,则返回"[object Undefined]".
2 如果this的值为null,则返回"[object Null]".
3 让O成为调用ToObject(this)的结果.
4 让class成为O的内部属性[[Class]]的值.
5 返回三个字符串"[object ", class, 以及 "]"连接后的新字符串.
可以看出,比ES3多了1,2,3步.第1,2步属于新规则,比较特殊,因为"Undefined"和"Null"并不属于[[class]]属性的值。经统计,可返回的类型有"Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp", "String"比ES3多了2种分别是arguments对象的[[class]]成了"Arguments",而不是以前的"Object",还有就是多个了全局对象JSON,它的[[class]]值为"JSON"。
最后的最后提醒大家,Object.prototype.toString().call(param)返回的[object class]中class首字母是大写,像JSON这种甚至都是大写,所以,大家判断的时候可以都转换成小写,以防出错,Object.prototype.toString().call(param).toLowerCase()即可。
判断js中各种数据的类型方法之typeof与0bject.prototype.toString讲解的更多相关文章
- 判断js中的数据类型的几种方法
判断js中的数据类型有一下几种方法:typeof.instanceof. constructor. prototype. $.type()/jquery.type(),接下来主要比较一下这几种方法的异 ...
- 转:判断js中的数据类型的几种方法
判断js中的数据类型有一下几种方法:typeof.instanceof. constructor. prototype. $.type()/jquery.type(),接下来主要比较一下这几种方法的异 ...
- 如何判断js中的数据类型?
js六大数据类型:number.string.object.Boolean.null.undefined string: 由单引号或双引号来说明,如"string" number: ...
- 如何判断js中的数据类型
如何判断js中的数据类型:typeof.instanceof. constructor. prototype方法比较 如何判断js中的类型呢,先举几个例子: var a = "iamstri ...
- [转]如何判断js中的数据类型
原文地址:http://blog.sina.com.cn/s/blog_51048da70101grz6.html 如何判断js中的数据类型:typeof.instanceof. constructo ...
- 如何判断js中的数据类型(转)
如何判断js中的数据类型:typeof.instanceof. constructor. prototype方法比较 如何判断js中的类型呢,先举几个例子: var a = "iamstri ...
- 判断js中的数据类型
如何判断js中的数据类型:typeof.instanceof. constructor. prototype方法比较 如何判断js中的类型呢,先举几个例子: var a = "iamstri ...
- JS中String类型转换Date类型 并 计算时间差
JS中String类型转换Date类型 1.比较常用的方法,但繁琐,参考如下:主要使用Date的构造方法:Date(int year , int month , int day)<script& ...
- Angular.js中处理页面闪烁的方法详解
Angular.js中处理页面闪烁的方法详解 前言 大家在使用{{}}绑定数据的时候,页面加载会出现满屏尽是{{xxx}}的情况.数据还没响应,但页面已经渲染了.这是因为浏览器和angularjs渲染 ...
随机推荐
- 使用CompletionService结合ExecutorService批处理任务
CompletionService用于提交一组Callable任务,其take方法返回已完成的一个Callable任务对应的Future对象. 如果你向Executor提交了一个批处理任务,并且希望在 ...
- tcl/tk
http://blog.csdn.net/dulixin/article/category/365058 http://blog.csdn.net/dulixin/article/category/3 ...
- CentOS 7下的软件安装方法及策略
一些废话 2010年开始正式接触Linux,入门发行版是Ubuntu 10.10,后来过渡到Ubunu 11.04,这其中也尝试了很多其他主流的发行版.进入实验室之后,开始用CentOS 5,然后是C ...
- Escape Sequences in String
Code Output \' single quote \" double quote \\ backslash \n newline \r carriage return \t tab ...
- ASP实现用年月日时分秒和两位随机数字来作为上传文件名的函数
Public Function GetNewFileName() dim ranNum dim dtNow dtNow=Now() randomize ranNum=int(90*rnd)+10 Ge ...
- ASP.NET MVC 4应用程序文件夹
App_Start It has configuration classes to reduce clutter code in the Global.asax 它包含了配置类来减少在Global.a ...
- 缓存(之一) 使用Apache Httpd实现http缓存
http://www.tuicool.com/articles/EFfeu2 HTTP性能的问题与方案 一个最终用户访问一个网页,从浏览器发出请求,到接受请求,时间大体上消耗在了以下几个部分: 建立t ...
- Docker Machine, Compose, and Swarm: How They Work Together
The three tools are now neatly packaged into what’s called the Docker Toolbox. Docker Machine1/ crea ...
- 转:C# 泛型编程之泛型类、泛型方法、泛型约束
C# 泛型编程之泛型类.泛型方法.泛型约束 分类: asp.net c#2012-08-07 17:36 5998人阅读 评论(0) 收藏 举报 c#编程classobject编译器struct 泛型 ...
- 常用AWK命令
常用AWK命令 Awk is a programming language which allows easy manipulation of structured data and the gene ...