gpt4 book ai didi

javascript - function(a, b) 的值是多少?

转载 作者:搜寻专家 更新时间:2023-11-01 04:38:07 25 4
gpt4 key购买 nike

我正在测试 JavaScript 中的模块示例:The Good Parts。不知道谁在function(a, b)中传入了a和b。它以某种方式起作用。

Function.prototype.method = function(name, f) {
this.prototype[name] = f;
return this;
}
String.method('de', function() {
var entity = {
lt : '<',
gt : '>'
};
return function() {
return this.replace(/&([^&;]+);/g, function(a, b) {
document.write("<br> a=" + a + " b=" + b);
var r = entity[b];
return typeof r === 'string' ? r : a;
});
};
}());
document.write("<br>" + '&lt;&gt'.de());

最佳答案

要了解正在发生的事情,必须非常仔细地查看实际发生的事情。

Function.prototype.method = function(name, f) {
this.prototype[name] = f;
return this;
}

这部分很清楚,它是扩展任何对象的原型(prototype)的“捷径”。

魔术发生在代码的第二部分,先前定义的函数提供了一个自执行函数作为第二个参数!

String.method('de', function() {
var entity = {
lt : '<',
gt : '>'
};
return function() {
return this.replace(/&([^&;]+);/g, function(a, b) {
// "this" will refer to the object the function is bound to.
document.write("<br> a=" + a + " b=" + b);
var r = entity[b];
return typeof r === 'string' ? r : a;
});
};
}()); <-- The magic happens here!

这意味着,JavaScript 解释器将使用“第一个内部”函数(直接提供给 String.method)的返回值作为实际函数,因为“第一个内部”函数在将其分配给 String.prototype 之前执行。

下面的代码做同样的事情,但在本地范围内多放了一个变量 (de)。上面的方法不会污染作用域,是一种更优雅的实现方式。您甚至可以将其进一步解包,将 entity 放入本地范围。

var de = function() {
var entity = {
lt : '<',
gt : '>'
};
return function() {
return this.replace(/&([^&;]+);/g, function(a, b) {
// "this" will refer to the object the function is bound to.
document.write("<br> a=" + a + " b=" + b);
var r = entity[b];
return typeof r === 'string' ? r : a;
});
};
};
String.method('de', de());

现在回答关于 ab 如何发挥作用的问题!这与当传递的第二个参数是函数时 String.replace 的行为有关。 link评论中提供的 DCoder 解释得很好!参数a是整个匹配的子串,b是第一个匹配的“带括号的子匹配”。

关于javascript - function(a, b) 的值是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13098142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com