Skip to content Skip to sidebar Skip to footer

Why Doesn't RegExp Prototype Work Properly?

RegExp.prototype only work for: var a = /abc/g a.tester() var b = /xyz/ b.tester() Doesn't work with: /abc/g.tester() /abc/.tester() Is there a way I can fix this so all three

Solution 1:

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


Post a Comment for "Why Doesn't RegExp Prototype Work Properly?"