1、instanceof
var simpleStr = "This is a simple string";
var myString = new String();
var newStr = new String("String created with constructor");
var myDate = new Date();
var myObj = {};
var myNonObj = Object.create(null);
simpleStr instanceof String; // 返回 false, 非对象实例,因此返回 false
myString instanceof String; // 返回 true
newStr instanceof String; // 返回 true
myString instanceof Object; // 返回 true
myObj instanceof Object; // 返回 true, 尽管原型没有定义
({}) instanceof Object; // 返回 true, 同上
myNonObj instanceof Object; // 返回 false, 一种创建非 Object 实例的对象的方法
myString instanceof Date; //返回 false
myDate instanceof Date; // 返回 true
myDate instanceof Object; // 返回 true
myDate instanceof String; // 返回 false
2、typeof
注意:typeof null
返回 "object"
操作符返回一个字符串,表示未经计算的操作数的类型
typeof只能判断对象类型中的function,其它都为objecct
3、object原型链上的toString方法
const a = {}
const b = {}
const c = {}
b[a] = 1
b[c] = 2
console.log(b[a]) //2
console.log(Object.prototype.toString.call(this)) //[object Object]
console.log(a.toString()) //[object Object]
const fn = function () {}
console.dir(fn.__proto__)
console.log(fn.__proto__.toString) //ƒ toString() { [native code] }
console.log(Function.prototype.toString) //ƒ toString() { [native code] }
function getDataType(data) {
const type = Object.prototype.toString.call(data)
return console.log(type.substring(8, type.length - 1))
}
getDataType({}) //Object
getDataType([]) //Array
getDataType(true) //Boolean