gpt4 book ai didi

Javascript 正则表达式原型(prototype)

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:25:16 26 4
gpt4 key购买 nike

为什么 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com