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?
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)
                        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);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With