Regexp shows unexpected type error in javascript

This is rather strange, I don’t know why this is happening, but here it is. When I do this:

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

It works great. But when I do something like the following, I get an error

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

The error I am getting is this:

TypeError: RegExp.prototype.test method called by incompatible receiver [object window]

I do not know what this has to do with Window here ... any idea?

+4
source share
3 answers

When you execute /^\d+$/.test('16') , you call the test function with your regular expression as the this object (i.e., as a method call to the object).

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

To reproduce the first behavior, you will need to do this:

 var r = /^\d+$/; var t = r.test; t.call(r, 16); 
+7
source

Alternatively, you can use bind to create a new function that uses a regular expression like this :

 var r = /^\d+$/; var t = r.test.bind(r) t(16) 
+7
source

I saw that this happened when I wanted to filter the array using regular expression matching and fixed it with bind :

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

What result:

 ['a', 'A'] 
0
source

Source: https://habr.com/ru/post/1435559/


All Articles