What happens when I set the same variable to the same regex value in multiple statements?

前端 未结 3 1270
青春惊慌失措
青春惊慌失措 2020-12-20 05:29

Let\'s say I do this:

re = /cat/;
re = /cat/;

From reading Zakas\' book about Javascript, it seems that when executing the second line, no

3条回答
  •  自闭症患者
    2020-12-20 06:25

    Either the author is mistaken or Javascript has changed significantly since it was written, because that's not how it works now. See How often does JavaScript recompile regex literals in functions? for a number of answers that go into detail about this.

    I suspect the author may have confused regexp compilation with RegExp objects. When the compiler sees a regexp literal, it can compile it once. Then it generates code that runs each time through the loop to create a new object that uses that compiled regexp to perform the matching. But each RegExp object has its own state.

    Notice that he says he's describing EcmaScript 3. That's a very old edition of EcmaScript, originally published in 1999. EcmaScript 5 is from 2009 (ES4 was abandoned during development), and that's what most browsers have implemented for several years, with ES6 adoption being phased in during the past couple of years. Maybe ES3 behaved the way he describes, but more recent editions don't.

提交回复
热议问题