dangerChihuahua007
dangerChihuahua007

Reputation: 20915

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

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 literals vary in the lastIndex property?

var a = /a/g;
var b = /a/g;

a.lastIndex = 3;
document.write(b.lastIndex);​

JS Fiddle

0 is outputted as opposed to 3.

Upvotes: 2

Views: 80

Answers (2)

Paul
Paul

Reputation: 141887

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).

Upvotes: 3

Dan Tao
Dan Tao

Reputation: 128387

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).

Upvotes: 0

Related Questions