Object.prototype.toString vs typeof

var start = new Date(); for(var i = 0; i < 100000000; i++){ Object.prototype.toString.call(1)}; var end = new Date(); console.log(end-start);

执行时间:33526

var start = new Date(); for(var i = 0; i < 100000000; i++){ typeof 1}; var end = new Date(); console.log(end-start);

执行时间:212

由此可见typeof的效率高出很多,这个在jQuery源代码也有所体现:

type: function( obj ) {
    if ( obj == null ) {
        return String( obj );
    }
    return typeof obj === "object" || typeof obj === "function" ?
        class2type[ core_toString.call(obj) ] || "object" :
        typeof obj;
}

只有检测到对象是object或者function的时候,才会去调用Object.prototype.toString,否则直接调用typeof。

----------------------------------------

以下为typeof和Object.prototype.toString的返回值对比:

typeof []; // object
typeof {}; // object
typeof ''; // string
typeof new Date() // object
typeof 1; // number
typeof function () {}; // function
typeof /test/i; // object
typeof true; // boolean
typeof null; // object
typeof undefined; // undefined
Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call({}); // [object Object]
Object.prototype.toString.call(''); // [object String]
Object.prototype.toString.call(new Date()); // [object Date]
Object.prototype.toString.call(1); // [object Number]
Object.prototype.toString.call(function () {}); // [object Function]
Object.prototype.toString.call(/test/i); // [object RegExp]
Object.prototype.toString.call(true); // [object Boolean]
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call(); // [object Undefined]

 参考链接:

https://toddmotto.com/understanding-javascript-types-and-reliable-type-checking/

posted @ 2016-09-01 10:48  liangzi4000  阅读(299)  评论(0编辑  收藏  举报