文章目录
一、toString()
toString()
方法返回一个表示该对象的字符串。Object.prototype.toString()
可以看出toString()
继承自Object
二、Object.prototype.toString()方法判断数据类型的原理
如果
toString()
方法在自定义对象中未被覆盖,toString()
返回[object type]
,其中type
是对象的类型。
2.1. toString方法没有被覆盖的情况
例如
Object,Math
他们直接调用toStirng()
方法,可以直接判断出来数据类型
obj.toString(); // "[object Object]"
Math.toString(); // "[object Math]"
2.2. toString方法被覆盖的情况
Number、Boolean、String、Array、Date、RegExp、Function
这几种构造函数生成的对象,toString
方法都被覆盖了,所以他们无法使用toString()
方法判断数据类型
Boolean.prototype.hasOwnProperty("toString"); // true
String.prototype.hasOwnProperty("toString"); // true
Array.prototype.hasOwnProperty("toString"); // true
Date.prototype.hasOwnProperty("toString"); // true
RegExp.prototype.hasOwnProperty("toString"); // true
Function.prototype.hasOwnProperty("toString"); // true
var num = new Number("123sd");
num.toString(); // 'NaN'
var str = new String("12df");
str.toString(); // '12df'
var bool = new Boolean("fd");
bool.toString(); // 'true'
var arr = new Array(1, 2);
arr.toString(); // '1,2'
var d = new Date();
d.toString(); // "Sun Jul 22 2018 12:38:42 GMT+0800 (中国标准时间)"
var func = function () {};
func.toString(); // "function () {}"
三、使用 toString() 检测对象类型
为了每个对象都能通过
Object.prototype.toString()
来检测,需要以Function.prototype.call()
或者Function.prototype.apply()
的形式来调用,传递要检查的对象作为第一个参数。
至于
call
的作用,帮助执行一次Object.prototype.toString
方法,并且将函数内部的this
替换为call
的第一个参数
Object.prototype.toString.call(new Date()); // [object Date]
Object.prototype.toString.call(new String()); // [object String]
Object.prototype.toString.call(Math); // [object Math]
//Since JavaScript 1.8.5
Object.prototype.toString.call(undefined); // [object Undefined]
Object.prototype.toString.call(null); // [object Null]
3.1、方法封装
export const getObjType = (obj) => {
const toString = Object.prototype.toString;
const map = {
"[object Boolean]": "boolean",
"[object Number]": "number",
"[object String]": "string",
"[object Function]": "function",
"[object Array]": "array",
"[object Date]": "date",
"[object RegExp]": "regExp",
"[object Undefined]": "undefined",
"[object Null]": "null",
"[object Object]": "object",
};
return map[toString.call(obj)];
};
四、call详解
帮助执行一次函数,并且将函数内部的
this
替换为call
的第一个参数
function.call(thisArg, arg1, arg2, ...)
[thisArg]
在func
函数运行时使用的this
值。
let objCall = {
name: "我是 Call",
};
function fn() {
console.log("参数 => ", ...arguments);
console.log("name => ", this.name);
}
fn.call(objCall, 1, 2, 3);
// 参数 => 1 2 3
// name => 我是Call