J A*_*Any 5 javascript concept
我正在测试JavaScrit的模块示例:好的部件.我不知道谁在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>" + '<>'.de());
Run Code Online (Sandbox Code Playgroud)
要了解正在发生的事情,必须非常仔细地观察实际做了什么。
Function.prototype.method = function(name, f) {
this.prototype[name] = f;
return this;
}
Run Code Online (Sandbox Code Playgroud)
这部分很清楚,它是扩展任何对象的 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!
Run Code Online (Sandbox Code Playgroud)
这意味着,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());
Run Code Online (Sandbox Code Playgroud)
现在回答您关于如何a发挥b作用的问题!String.replace这与传递的第二个参数是函数时的行为有关。评论中提供的链接 DCoder 很好地解释了这一点!参数a是整个匹配的子字符串,b是第一个匹配的“括号子匹配”。