Javascript 正则表达式原型(prototype)

标签 javascript regex prototype

为什么 Chrome 的控制台为 RegExp 的原型(prototype)显示 /(?:)/

console.log(RegExp.prototype);
console.log(/a/.__proto__);

这是特定于实现的东西吗? IE 正在显示 //

这只是出于好奇而提出的问题。当我遇到这个时,我试图在javascript中查看正则表达式的所有原型(prototype)方法。当然,我找到了查找这些方法的其他方法,但这让我想知道为什么会显示此结果。

我希望之前没有人问过这个问题——在 Stackoverflow 上没有找到任何东西。谢谢!

最佳答案

Relevant section from spec

The RegExp prototype object is itself a regular expression object; its [[Class]] is "RegExp". The initial values of the RegExp prototype object’s data properties (15.10.7) are set as if the object was created by the expression new RegExp() where RegExp is that standard built-in constructor with that name.

Then we go to new RegExp() section ,这与使用空字符串调用它相同。所以现在我们有一个空的正则表达式对象作为原型(prototype)。

字符串表示 is defined to be :

Return the String value formed by concatenating the Strings "/", the String value of the source property of this RegExp object, and "/"; plus "g" if the global property is true, "i" if the ignoreCase property is true, and "m" if the multiline property is true.

NOTE The returned String has the form of a RegularExpressionLiteral that evaluates to another RegExp object with the same behaviour as this object.

它最终归结为 .source 属性(在 new RegExp section 中解释),它是实现定义的,只要它在用作正则表达式时表现相同:

Let S be a String in the form of a Pattern equivalent to P, in which certain characters are escaped as described below. S may or may not be identical to P or pattern; however, the internal procedure that would result from evaluating S as a Pattern must behave identically to the internal procedure given by the constructed object's [[Match]] internal property.

由于 new RegExp("(?:)")new RegExp("") 的行为相同,因此 chrome 和 IE 都正确地遵循了规范。该规范甚至提到了这种特定情况作为示例:

If P is the empty String, this specification can be met by letting S be "(?:)"

Chrome 的方式可以被认为是“更好的”,因为它似乎也可以用作正则表达式文字:/(?:)/ 是一个有效的正则表达式文字,而 //开始一行评论。

关于Javascript 正则表达式原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18314273/

相关文章:

regex - 转到正则表达式以匹配带有括号的标签

android - 在 Kotlin 中使用正则表达式获取字符串中模式的索引

javascript - 处理超出范围的矩对象

dart - 无法使原始路径相对并且没有这样的文件或目录

javascript - 在 ajax success() 函数中创建时,Bootstrap 警报刷新并消失

javascript - 无法在谷歌地球中渲染kml文件

javascript - 为什么 ko.observableArray.length 不返回底层数组的长度?

javascript - html5 和 js 中的地理定位 - 我拒绝但我想接受 - 如何重置?

javascript - 为什么这个 replace() 不替换 "my"?

javascript - 我可以在不使用 new 关键字的情况下构造 JavaScript 对象吗?