Skip to content

Object.prototype.toString.call() & typeof & instanceOf

Object.prototype.toString.call()

【可以检测任意类型,但是对于new实例会返回"[object Object]"】

  • 每一个继承 Object 的对象都有 toString 方法,会返回 [Object type],其中 type 为对象的类型。
  • 划重点: 除了 Object 类型的对象外,其他类型直接使用 toString 方法时,会直接返回内容的字符串,所以我们需要使用call或者apply方法来改变toString方法的执行上下文。
  • 【toString 内部大概是有把其他类型(除object)转换为原始对象类型的操作,改变它的执行上下文对象即可。】
js
Object.prototype.toString.call(undefined);
"[object Undefined]"

Object.prototype.toString.call(null);
"[object Null]"

Object.prototype.toString.call(123);
"[object Number]"

Object.prototype.toString.call('');
"[object String]"

Object.prototype.toString.call(true)
"[object Boolean]"

Object.prototype.toString.call(Symbol())
"[object Symbol]"

Object.prototype.toString.call(BigInt(1))
'[object BigInt]'

Object.prototype.toString.call({});
"[object Object]"

Object.prototype.toString.call([]);
"[object Array]"

Object.prototype.toString.call(function(){});
"[object Function]"

// 不能检测的自定义行为【比如new出来的实例永远返回[object Object]】
function f(name) {
    this.name=name;
}
var f1=new f('sadf');
console.log(Object.prototype.toString.call(f1));// [object Object]

instanceOf

【返回值为true/false】

  • 检测左边的对象是否存在它的原型链上

typeof

【只能检测object、function、还有基本数据类型(除null外)】

  • 简单提一下原理: 不同的对象在底层都表示为二进制, 在 JavaScript 中二进制前三位都为 0 的话会被判断为 object 类型, null 的二进制表示是全 0, 自然前三位也是 0, 所以执行 typeof 时会返回“object”。
js
    console.log(typeof a);    //'undefined'

    console.log(typeof(true));  //'boolean'

    console.log(typeof '123');  //'string'

    console.log(typeof 123);   //'number'

    console.log(typeof NaN);   //'number'

     console.log(typeof Symbol()); // 'symbol'
     
     console.log(typeof BigInt(123)) // 'bigint'

    var  fn = function(){};
    console.log(typeof(fn));  //'function'


    console.log(typeof(class c{}));  //'function'

    console.log(typeof null);  //'object'    

    var obj = new String();
    console.log(typeof(obj));    //'object'
    
    let reg = new RegExp()
    console.log(typeof reg) // 'object'
    console.log(typeof /a/) // 'object'
    
    let date = new Date()
    console.log(date) // 'object'