typeof
只能判断简单的数据类型
缺点:不能区分是数组还是对象,而且typeof null 也是一个对象。
instanceof
判断是否在原型链上。
原理:
- 判断左边变量的隐式原型(proto,也可以通过Object.getPrototypeOf()获取);
- 获取右边变量的显示原型(prototype);
- 判断是否相等,不行就递归遍历。
```javascript
function myInstanceof(instance, origin) {
if(instance == null) {
} const type = typeof instance; if(type !== ‘object’ && type !== ‘function’) {return false;
} let tempInstance = instance; while(tempInstance) {return false;
} return false; }if(tempInstance.__proto__ === origin.prototype) {
return true;
}
tempInstance = tempInstance.__proto__;
const res = myInstanceof([1,2,3], Object);
缺点:需要递归原型链
<a name="h1cDF"></a>
# constructor
```javascript
const val1 = 1;
console.log(val1.constructor); // [Function: Number]
缺点:
- 对null和undefined无效;
- 函数的constructor是不稳定的,重新prototype后,原有的constructor引用会丢失,会变成默认的Object
toString()
较常用 ```javascript function type(target) { const ret = typeof target; const template = { ‘[object Array]’: ‘array’, ‘[object Object]’: ‘object’, ‘[object Number]’: ‘number’, ‘[object Boolean]’: ‘boolean’, ‘[object String]’: ‘string’, }; if (target === null) { return ‘null’; } else if (ret == ‘object’) { const str = Object.prototype.toString.call(target); return template[str]; } else { return ret; } }
console.log(type({})); // object console.log(type(123)); // number console.log(type(‘123’)); // string ```