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

1 Answer 1

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 `.

Sign up to request clarification or add additional context in comments.

1 Comment

A good example of why getting into the habit of using semi colons is a good idea.

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.