【发布时间】:2015-08-11 00:01:00
【问题描述】:
我正试图将我的大脑包裹在闭包上。我一直在阅读 Javascript: the Good Parts,作者提供了这段代码 sn-p 用于向 String 对象添加“deentityify”方法,其想法是解码 HTML 编码符号:
// 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' 以前从最后一句中丢失,导致含义不清楚。
【问题讨论】:
-
试试
"&#123;".deentityify()- 只有当你在包含 HTML 实体的字符串上使用它时,该函数才会做任何有趣的事情。
标签: javascript methods parameters closures