Javascript: 传递给函数的参数是什么?

Javascript: What parameters are being passed to function?

我正在努力思考闭包问题。我一直在阅读 Javascript:好的部分,作者展示了这个代码片段,用于向 String 对象添加 'deentityify' 方法,其想法是解码 HTML-enocoded 符号:

// the method method:
Function.prototype.method = function(name, func) {
        if (! this.prototype[name]) {
                this.prototype[name] = func;
                return this;
        }
}

String.method('deentityify', function() {

        // entity table: maps entity names
        // to characters:
        var entity = {
                quot: '"',
                lt: '<',
                gt: '>',
        };

        // Return the deentityify method:
        return function() {
                return this.replace(/&([^&;]+);/g,
                        // What are a & b, how are they getting passed?!
                        function (a, b) {
                                //  console.log added by me, unsuccessfully:
                                console.log('a = ' + a);
                                console.log('b = ' + b);
                                var r = entity[b];
                                return typeof r === 'string' ? r : a;
                        }
                );
        };
}());

所以我明白这里发生的大部分事情,除了传递给函数的实际参数定义为 String.replace 的第二个参数。 'a' 和 'b' 是如何定义的?

直接调用 '"'.deentityify() 并没有显式传递任何参数。那么它们是如何定义的?作为一个次要问题,为什么 console.log() 用于记录 a 和 b 的值?有什么方法可以成功记录此类变量?

感谢您的帮助。

编辑:'not'之前在最后一句话中缺失,导致含义不明确。

.replace()函数可以用一个函数作为第二个参数来调用。当您这样做时,在正则表达式与从匹配过程中提取的参数成功匹配后调用该函数。

第一个参数始终是源字符串的整个匹配部分。后续参数表示正则表达式中的 "capturing groups"。

在本例中,正则表达式为/&([^&;]+);/g。这匹配一个 & 号后跟除 & 号或分号以外的任意数量的字符,然后是一个分号。前导 & 符号和尾随分号之间的字符是 "captured" 因为正则表达式的那部分被括号括起来。

因此,如果源字符串是

Hello &mdash; world!

然后匹配该正则表达式(一次)将产生:

  • &mdash; 作为整体匹配字符串
  • mdash 作为第一个(在本例中也是唯一的)捕获组的值。

因此:

"Hello &mdash; world!".replace(/&([^&;]+);/g, function(all, group) {
  alert("entire match: " + all + " group: " + group);
});

会根据我上面列出的内容显示一条消息。

现在,最重要的是,问题中的代码涉及另一层有趣的行为。 实际上 传递给 method() 函数的函数不是那个大的外部函数,而是 返回 的函数。返回的函数期望被调用,使得 this 是一个 String 实例;否则,对 this.replace() 的调用将不起作用。