0

RegExp.prototype only work for:

var a = /abc/g
a.tester()

var b = /xyz/
b.tester()

Doesn't work with:

  1. /abc/g.tester()
  2. /abc/.tester()


Is there a way I can fix this so all three can work?

Headsup
It needs to be a RegExp.prototype
Question: How does the native .test() do it?



What Works

RegExp.prototype.tester = function(s, v) {
  console.log("I'm working")
  console.log(this)
}

a = /abc/g
b = /xyz/
a.tester()
b.tester()




Problems

RegExp.prototype.tester = function(s, v) {
  console.log("I'm working")
  console.log(this)
}

/abc/g.tester() //This is a problem
/abc/.tester() //This is a problem
Allen Marshall
  • 381
  • 2
  • 10

1 Answers1

3

It's just a syntax error, not a problem with the prototypical inheritance (and calling .test instead of .tester wouldn't make a difference). Use semicolons!

RegExp.prototype.tester = function (s,v) {
    console.log("I'm working")
    console.log(this)
}; /*
 ^ */

/abc/g.tester(); // now it's not a problem
/abc/.tester();  // any more

What was happening here is that the parser interpreted your code as one large statement:

… = function(){…} / abc / g.tester() / abc / .tester();

Indeed the property access . after the division operator / is an unexpected token.

If you want to omit semicolons and let them be automatically inserted where ever possible needed, you will need to put one at the begin of every line that starts with (, [, /, +, - or `.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375