Underscore.js,为什么`isFunction`使用`||假的?
Underscore.js, why does `isFunction` use `|| false`?
Underscore.js (repo link to definition) 中 isFunction(object)
的可选覆盖,内容如下:
// Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
// IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
var nodelist = root.document && root.document.childNodes;
if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
_.isFunction = function(obj) {
return typeof obj == 'function' || false;
};
}
我比较困惑的是|| false
,为什么要在字符串比较之后呢?因为 typeof
总是 return 是一个字符串,所以应该没有歧义?
评论指出覆盖修复了一些 typeof
错误,在列出的平台上是否存在 typeof
不是 return 字符串的情况?
查看评论中涵盖的问题,#1621, #1929 and #2236。
简而言之,某些平台存在错误,其中 typeof
不是字符串,除非您将其存储在变量中。
|| false
在不引入额外变量的情况下解决了这个问题。
直接取自#1621:
在 IE8 中,使用变量一切正常:
var t = typeof obj
t === 'function' // false
t === 'object' // true
但没有一个,情况就不同了:
(typeof obj) === 'function' // true, but SHOULD be false
(typeof obj) === 'object' // true
上面概述的额外检查修复了错误。
Underscore.js (repo link to definition) 中 isFunction(object)
的可选覆盖,内容如下:
// Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
// IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
var nodelist = root.document && root.document.childNodes;
if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
_.isFunction = function(obj) {
return typeof obj == 'function' || false;
};
}
我比较困惑的是|| false
,为什么要在字符串比较之后呢?因为 typeof
总是 return 是一个字符串,所以应该没有歧义?
评论指出覆盖修复了一些 typeof
错误,在列出的平台上是否存在 typeof
不是 return 字符串的情况?
查看评论中涵盖的问题,#1621, #1929 and #2236。
简而言之,某些平台存在错误,其中 typeof
不是字符串,除非您将其存储在变量中。
|| false
在不引入额外变量的情况下解决了这个问题。
直接取自#1621:
在 IE8 中,使用变量一切正常:
var t = typeof obj
t === 'function' // false
t === 'object' // true
但没有一个,情况就不同了:
(typeof obj) === 'function' // true, but SHOULD be false
(typeof obj) === 'object' // true
上面概述的额外检查修复了错误。