Why do two regex literals in my Javascript vary on a property?

后端 未结 2 1882
后悔当初
后悔当初 2021-01-07 06:47

I read in Javascript: The Good Parts by Douglas Crockford that javascript regular expression literals share the same object. If so, then how come these two regex li

相关标签:
2条回答
  • 2021-01-07 07:21

    Section 7.8.5 of the ECMAScript Documentation makes it quite clear they are two different objects:

    7.8.5 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. A RegExp object may also be created at runtime by new RegExp (see 15.10.4) or calling the RegExp constructor as a function (15.10.3).

    0 讨论(0)
  • 2021-01-07 07:34

    Because they are different objects.

    document.write(a === b);
    

    Even this outputs false.

    Either Crockford was wrong, or he was right at the time but times have changed.

    I realize this isn't a particularly helpful or informative answer; I'm just pushing back on what I perceive as your disbelief that something Crockford wrote could be (now) false.

    Do you have a reference to that claim, by the way? Would be interesting to read it in context (I don't have the book).

    0 讨论(0)
提交回复
热议问题