克罗克福德的深化方法 - “好部件”第41页 [英] Crockford's deentityify method - p.41 of The Good Parts
问题描述
...
return this.replace( ...,
函数(a,b){
var r = ...
}
);
我想我明白了:
- this.replace传递了两个参数,正则表达式作为搜索值和函数来生成重置值;
- b用于访问属性实体对象;
- 返回
? r:a;
位确定是返回文本还是实体中相应属性的值。
- 返回
我根本得不到的是a& b作为参数提供给函数(a,b)
。什么叫这个功能? (我知道整个事情是自动执行的,但是这并不能真正为我清除它,我猜我在问这个函数是如何被调用的?)
如果有人有兴趣通过类似于这个,我真的很感激它,我怀疑其他人也可能。
以下是方便的代码:
String.method('deentityify',function(){
var entity = {
quot;''',
lt;',
gt:'>'
};
return function(){
return this.replace(
/ &([^& ;;] +); / g,
函数(a,b){
var r = entity [b];
返回typeof r ==='string '?r:a;
}
);
};
}());
a 不是数字偏移量,它是匹配子字符串。 $ b
b
(在这种情况下)是第一个分组,即匹配减去周围的&
和;
。
该方法检查以确保实体存在,并且它是一个字符串。如果是,那就是重置价值,否则它会被原来的价值减去&
和;
In a fit of self-improvement, I'm reading (and rereading) TGP by Señor Crockford. I cannot, however, understand the middlemost part of his deentityify method.
...
return this.replace(...,
function (a, b) {
var r = ...
}
);
I think I understand that:
- this.replace is passed two arguments, the regex as the search value and the function to generate the replacement value;
- the b is used to access the properties in the entity object;
- the return
? r : a;
bit determines whether to return the text as is or the value of the appropriate property in entity.
What I don't get at all is how the a & b are provided as arguments into function (a, b)
. What is calling this function? (I know the whole thing is self-executing, but that doesn't really clear it up for me. I guess I'm asking how is this function being called?)
If someone was interested in giving a blow by blow analysis akin to this, I'd really appreciate it, and I suspect others might too.
Here's the code for convenience:
String.method('deentityify', function ( ) {
var entity = {
quot: '"',
lt: '<',
gt: '>'
};
return function () {
return this.replace(
/&([^&;]+);/g,
function (a, b) {
var r = entity[b];
return typeof r === 'string' ? r : a;
}
);
};
}());
a
isn't the numerical offset, it's the matched substring.
b
(in this case) is the first grouping, i.e., the match minus the surrounding &
and ;
.
The method checks to make sure the entity exists, and that it's a string. If it is, that's the replacement value, otherwise it's replaced by the original value, minus the &
and ;
这篇关于克罗克福德的深化方法 - “好部件”第41页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!