Do RegExps made by expression literals share a single instance?

拜拜、爱过 提交于 2019-11-28 11:01:14

问题


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

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.


回答1:


No, they are not shared. From the spec on Regular Expression Literals:

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.

However, this changed with ES5. Old ECMAScript 3 had a different behavior:

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.

This was supposed to share the compilation result of the regex engine across evaluations, but obviously led to buggy progams.

You should throw your book away and get a newer edition.



来源:https://stackoverflow.com/questions/28183907/do-regexps-made-by-expression-literals-share-a-single-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!