Wrapping regex's with proxies isn't working

Claude Pache claude.pache at gmail.com
Thu Nov 10 14:20:42 UTC 2016


> Le 10 nov. 2016 à 14:59, Angel Scull <scull06 at gmail.com> a écrit :
> 
> Hello,
> 
> I’ve tried this code and seems that there is some weird type checking somewhere that causes this exception. 
> 
> TypeError: Method RegExp.prototype.exec called on incompatible receiver [object Object]
> 
> 
> let pattern = /^[a-zA-Z0-9\-\._]+@[a-zA-Z0-9\-_]+(\.?[a-zA-Z0-9\-_]*)\.[a-zA-Z]{2,3}$/;
> 
> let patternProxy = new Proxy(pattern,{});
> 
> patternProxy.test('myusername at mycompany.com')

This is because the `exec` method of `pattern` is internally called with `patternProxy` as its receiver (i.e, its "this argument"), and `patternProxy` is not a regexp. This is a general issue with proxies, and not a bug.

A simple adhoc workaround is to bind the `exec` method of that particular `pattern` to `pattern` itself:

```js
pattern.exec = pattern.exec.bind(pattern)
```

—Claude


More information about the es-discuss mailing list