---
title: "区分复杂数据类型Object.prototype.toString.call()"
author: "小丑鱼0703"
date: "2015-02-09T14:16:40Z"
tags: []
categories: ["Web前端"]
slug: "object-prototype-tostring-call"
draft: false
lastmod: "2015-02-26T17:11:58Z"
id: 2184598
url: "https://wangjingyi.iteye.com/blog/2184598"
---

在 JavaScript 里使用 typeof 来判断数据类型，只能区分基本类型，即 “number”，”string”，”undefined”，”boolean”，”object” 五种。对于数组、函数、对象来说，其关系错综复杂，使用 typeof 都会统一返回 “object” 字符串。
所以：要想区别对象、数组、函数单纯使用 typeof 是不行的。


```js
[b] Object.prototype.toString.call() [/b]
```

ECMA 5.1 中关于该方法的描述是这样的：
When the toString method is called, the following steps are taken:
If the this value is undefined, return ““.
If the this value is null, return ““.
Let O be the result of calling ToObject passing the this value as the argument.
Let class be the value of the ] internal property of O.
Return the String value that is the result of concatenating the three Strings ““.

ECMAScript 5 中，为了方便，对 null 和 undefined 调用 Object.prototype.toString 方法， 其返回值由 Object 变成了 Null 和 Undefined。方法结果如下：

```js

Object.prototype.toString.call(123);//[object number]
Object.prototype.toString.call('123'); //[object string]
Object.prototype.toString.call(undefined);//[object undefined]
Object.prototype.toString.call(null);//[object null]
Object.prototype.toString.call(true);//[object boolean]
Object.prototype.toString.call({});//[object object]
Object.prototype.toString.call([]); //[object array]
Object.prototype.toString.call(function(){}); //[object function]

```