繁体   English   中英

为什么RegExp原型无法正常工作?

[英]Why doesn't RegExp Prototype work properly?

RegExp.prototype仅适用于:

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

var b = /xyz/
b.tester()

不适用于:

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


有什么办法可以解决这个问题,所以这三个都可以工作吗?

小心
它必须是RegExp.prototype
问题:本机.test()如何执行?



什么有效

 RegExp.prototype.tester = function(s, v) { console.log("I'm working") console.log(this) } a = /abc/g b = /xyz/ a.tester() b.tester() 




问题

 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 

这只是语法错误,而不是原型继承的问题(调用.test而不是.tester不会有任何区别)。 使用分号!

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

这里发生的是解析器将您的代码解释为一条大语句:

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

确实是财产通道. 在除法运算符/是意外标记。

如果你想省略分号,并让他们自动插入需要的地方有可能 ,您将需要把一个在开始每一个开头线([/+-`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM