与数字,字符串和布尔值相反,其中文字是原始数据类型,并且具有无缝类型转换的对应的Number,String和Boolean对象是正则表达式文字RegExp对象的匿名实例,或者是正则表达式被视为原始数据无缝类型转换为RegExp?
“完整的参考Javascript,第2版,鲍威尔和施耐德(MH)”与自己相矛盾 – 在一个地方,作者说,/ regex /在需要时自动地被打包成RegExp,而在另一个地方他们说/ regex /只是一个RegExp的实例!
编辑:请提供可靠来源的参考
解决方法
A regular expression literal is an input element that is converted to a RegExp object 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.
没有原始的正则表达式类型以与字符串或数字相同的方式自动填充到对象.
但是请注意,并不是所有的浏览器都会实现“每个立即实例化”的行为,包括Safari和IE6(以及可能的更新版本),因此便携式代码不应该依赖于它.堕胎的ECMAScript 4草案would have changed the behavior与这些浏览器相匹配:
In ES3 a regular expression literal like
/a*b/mg
denotes a single unique RegExp object that is created the first time the literal is encountered during evaluation. In ES4 a new RegExp object is created every time the literal is encountered during evaluation.
另外,一些浏览器(Firefox <3,Safari)报告typeof / regex / as“function”,所以可移植代码应该避免使用instanceof对RegExp实例的typeof.