6

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?

3 Answers 3

10

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, this is the one you want if you are trying to pass a regex test into a callback
9

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

Comments

0

I saw this come up when I wanted to filter an array by things matching a regular expression, and fixed it using bind:

var items = ['a', 'b', 'c', 'A'];
var pattern = new RegExp('^a$', 'i');
var matches = items.filter(pattern.test.bind(pattern));
console.log(matches);

Which results as:

['a', 'A']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.