2012-05-01 22 views
10

引擎蓋下展望UnderscoreJS,我看到:爲什麼UnderscoreJS使用toString.call()而不是typeof?

_.isFunction = function(obj) { 
    return toString.call(obj) == '[object Function]'; 
    }; 

    _.isString = function(obj) { 
    return toString.call(obj) == '[object String]'; 
    }; 

    _.isNumber = function(obj) { 
    return toString.call(obj) == '[object Number]'; 
    }; 

這似乎是一個奇怪的選擇。爲什麼不使用typeof來確定值是字符串,函數還是數字?使用toString會有性能提升嗎? typeof不被舊版瀏覽器支持?

+0

自1996年版本1.1以來,'typeof'已存在於每個版本的JavaScript中。 –

回答

13

實際上,這是因爲通過檢查toString檢查[[Class]]會更快。也有可能是失誤少,因爲的toString給你確切的類...

檢查:

var fn = function() { 
    console.log(typeof(arguments)) // returns object 
    console.log(arguments.toString()) // returns object Arguments 
} 

你可以看到下劃線的typeof基準VS這裏的toString:

http://jsperf.com/underscore-js-istype-alternatives

還有一些github問題有更好的解釋:

https://github.com/documentcloud/underscore/pull/332

https://github.com/documentcloud/underscore/pull/321

編輯1:

你也可以查看這篇大文章:

http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/

+0

偉大的參考。謝謝! –

+1

/!\ http://jsperf.com/underscore-js-istype-alternatives/7(?DriverDan的回答) – BeauCielBleu

2

drinchev的回答是部分正確。 toString目前是比在大多數瀏覽器中使用typeOf要慢。使用typeOf的See the 7th revision of the test he posted。兩者仍然非常快,但在大多數情況下,這種性能差異不會顯而易見,並且折衷值比duck typing/typeOf更符合規格。

Underscore pull request 321(該drinchev列出)深入討論了權衡和他們爲什麼決定使用toString。

相關問題