typeof

只能判断简单的数据类型
缺点:不能区分是数组还是对象,而且typeof null 也是一个对象。

instanceof

判断是否在原型链上。
原理:

  1. 判断左边变量的隐式原型(proto,也可以通过Object.getPrototypeOf()获取);
  2. 获取右边变量的显示原型(prototype);
  3. 判断是否相等,不行就递归遍历。 ```javascript function myInstanceof(instance, origin) { if(instance == null) {
    1. return false;
    } const type = typeof instance; if(type !== ‘object’ && type !== ‘function’) {
    1. return false;
    } let tempInstance = instance; while(tempInstance) {
    1. if(tempInstance.__proto__ === origin.prototype) {
    2. return true;
    3. }
    4. tempInstance = tempInstance.__proto__;
    } return false; }

const res = myInstanceof([1,2,3], Object);

  1. 缺点:需要递归原型链
  2. <a name="h1cDF"></a>
  3. # constructor
  4. ```javascript
  5. const val1 = 1;
  6. console.log(val1.constructor); // [Function: Number]

缺点:

  1. 对null和undefined无效;
  2. 函数的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 ```