"if(!''.replace(/ ^ /,String))"是做什么的?

tba*_*tba 17 javascript regex

浏览缩小的Javascript代码时,我经常会看到以下语句:

if (!''.replace(/^/, String)) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这是做什么的?似乎任何符合ECMA的JS解释器都将替换字符串的开头String(''),这仍然会导致一个空字符串,其否定是true.

在什么情况下行为会有所不同?

Lep*_*eus 18

这似乎来自包装工,例如Dean Edwards javascript packer

那么,让我们下载代码,看看它说的是什么......

// code-snippet inserted into the unpacker to speed up decoding
const JSFUNCTION_decodeBody =
//_decode = function() {
// does the browser support String.replace where the
//  replacement value is a function?

'    if (!\'\'.replace(/^/, String)) {
        // decode all the values we need
        while ($count--) {
            $decode[$encode($count)] = $keywords[$count] || $encode($count);
        }
        // global replacement function
        $keywords = [function ($encoded) {return $decode[$encoded]}];
        // generic match
        $encode = function () {return \'\\\\w+\'};
        // reset the loop counter -  we are now doing a global replace
        $count = 1;
    }
';
Run Code Online (Sandbox Code Playgroud)

它似乎检查当前浏览器是否支持回调作为第二个参数replace(),如果是,则利用它来加快速度.

作为其余部分,Stringjavascript是一个函数,就是你在使用时使用的函数var foo = String('bar');,尽管你可能很少使用该语法.