表达式文字生成的RegExps是否共享一个实例? [英] Do RegExps made by expression literals share a single instance?
问题描述
以下代码段(来自Crockford的 Javascript:The Good Parts )演示了由正则表达式文字构成的RegExp对象共享一个实例:
The following snippet of code (from Crockford's Javascript: The Good Parts) demonstrates that RegExp objects made by regular expression literals share a single instance:
function make_a_matcher( ) {
return /a/gi;
}
var x = make_a_matcher( );
var y = make_a_matcher( );
// Beware: x and y are the same object!
x.lastIndex = 10;
document.writeln(y.lastIndex); // 10
问题:这与其他文字相同吗?我尝试修改上面的代码以使用字符串"string"
,但是遇到了很多错误.
Question: Is this the same with any other literals? I tried modifying the code above to work with the string "string"
, but got a bunch of errors.
推荐答案
否,它们没有共享.根据正则表达式文字 的的规范:
No, they are not shared. From the spec on Regular Expression Literals:
正则表达式文字是将输入元素转换为RegExp对象(请参见15.10)的方法.每次对文字进行求值.程序中的两个正则表达式文字求和为正则表达式对象,即使这两个文字的内容相同,它们也永远不会以===的形式进行比较.
A regular expression literal is an input element that is converted to a RegExp object (see 15.10) each time the literal is evaluated. Two regular expression literals in a program evaluate to regular expression objects that never compare as === to each other even if the two literals' contents are identical.
但是,ES5改变了这种情况. 旧的ECMAScript 3 具有不同的行为:
However, this changed with ES5. Old ECMAScript 3 had a different behavior:
正则表达式文字是一种输入元素,在扫描时会转换为RegExp对象(第15.10节).在开始评估包含的程序或功能之前创建对象.对文字的评估会产生对该对象的引用;它不会创建新对象.程序中的两个正则表达式文字求和为正则表达式对象,即使这两个文字的内容相同,它们也永远不会以===的形式进行比较.
A regular expression literal is an input element that is converted to a RegExp object (section 15.10) when it is scanned. The object is created before evaluation of the containing program or function begins. Evaluation of the literal produces a reference to that object; it does not create a new object. Two regular expression literals in a program evaluate to regular expression objects that never compare as === to each other even if the two literals' contents are identical.
这是本来应该在评估之间共享正则表达式引擎的编译结果,但显然导致了您应该将书扔掉并获得更新的版本.
You should throw your book away and get a newer edition.
这篇关于表达式文字生成的RegExps是否共享一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!