Eric
Eric

Reputation: 2275

Is the JavaScript RegExp implicit method deprecated?

So everyone knows what I mean by "implicit methods"? They're like those default properties from the Windows COM days of yore, where you could type something like

val = obj(arguments)

and it would be interpreted as

val = obj.defaultMethod(arguments)

I just found out JavaScript has the same thing: the default method of a RegExp object appears to be 'exec', as in

/(\w{4})/('yip jump man')[1]
==> jump

This even works when the RegExp object is assigned to a variable, and even when it's created with the RegExp constructor, instead of /.../, which is good news to us fans of referential transparency.

Where is this documented, and/or is it deprecated?

Upvotes: 2

Views: 271

Answers (2)

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827694

This feature is non-standard, some implementations like the Mozilla (Spidermonkey and Rhino) and the Google Chrome (V8) include it, but I would highly discourage its usage, because it isn't part of the specification.

Those implementations make RegExp objects callable, and invoking those objects is equivalent to call the .exec method.

In Chrome (and Firefox 2.x) even when you use the typeof operator with a RegExp object, you get "function" (because they implement the [[Call]] internal method).

typeof /foo/ == "function"; // true

Also IMO I don't see the benefit of using:

regexp(str);

Versus:

regexp.exec(str);

This is slightly documented here by Mozilla.

Upvotes: 6

Casey Chu
Casey Chu

Reputation: 25463

Well, all functions are objects, so you can do this:

var obj = function () {
    alert('Doing my default!');
};
obj.prop1 = 'Hello world';
obj.prop2 = function () {
    alert('Other method');
};

obj(); // 'Doing my default!'
alert(obj.prop1); // 'Hello world'
obj.prop2(); // 'Other method'

Upvotes: 0

Related Questions