您的位置:首页 > 移动开发 > Objective-C

Object.prototype.toString vs typeof

2016-09-01 10:48 411 查看
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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐