Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regexp showing unexpected Type error in javascript

This is quite bizarre, no idea why it happens, but here it is. When I do this:

/^\d+$/.test('16')

it works fine. But when I do something like the following, I get an error

var t = /^\d+$/.test;
t('16');

The error I get is this:

TypeError: Method RegExp.prototype.test called on incompatible receiver [object Window]

I don't know what it has got to do with Window over here....any idea?

like image 461
Parth Thakkar Avatar asked Sep 21 '12 18:09

Parth Thakkar


2 Answers

Alternatively, you can use bind to create a new function that uses the regex as this:

var r = /^\d+$/;
var t = r.test.bind(r)
t(16)
like image 118
Sjoerd Avatar answered Oct 06 '22 06:10

Sjoerd


When you do /^\d+$/.test('16') you are invoking the test function with your regexp as the this object (i.e. as a method invocation on an object).

When you run t(16) you have no object specified, and so this defaults to the top object, which is window.

To replicate the first behavior you'd have to do this:

var r = /^\d+$/;
var t = r.test;
t.call(r, 16);
like image 23
johusman Avatar answered Oct 06 '22 08:10

johusman