【问题标题】:Assigning a regex's test function fails分配正则表达式的测试函数失败
【发布时间】:2019-12-14 22:28:32
【问题描述】:

为什么(/x/.test)("x") 可以工作,但尝试使用(t=/x/.test)("x")t=/x/.test;t("x")test 函数提供替代名称会失败?

Firefox 给我一个TypeError: undefined is not a non-null object,而 Chrome 给我一个Uncaught TypeError: Method RegExp.prototype.test called on incompatible receiver undefined

我知道(t=s=>/x/.test(s))("x")t=s=>/x/.test(s);t("x") 可以工作,但我试图理解为什么上面没有。

【问题讨论】:

  • 我以前也遇到过这种情况。它与本地类有关。基本上,如果您将类原型中的函数分配给变量,它将失去其“this”值,从而中断。
  • 那是因为你打错了this。你可以使用Function.prototype.bindconst t = function(expr) {return expr.test.bind(expr);}(/X/);
  • @AluanHaddad 你能不能把它充实一点,让它成为一个答案?也许进一步解释 this 位,因为我的代码不包含任何提及 this...

标签: javascript regex function assign return-type


【解决方案1】:

我再解释一下:/x/.test 或 (/x/.test) 这个表达式执行如下:

  /x/: a regular expression object is created. Similar to: new  RegExp (/x/).


 .test: The RegExp "test()" method is invoked. The string parameter of "test" method is mandatory. Not finding the parameterThen it returns error.

为什么会这样:function f (s) {}; g = f; 因为您将函数 f 分配给变量 g。该赋值不执行 f。与 g = f() 不同的是,在这种情况下 g 将具有函数 f 返回的值。

为什么它不起作用:t = /x/.test 因为 /x/ 正在创建 RegExp 对象或调用其构造函数。然后,当返回此对象时,它会找到对 test 的调用,因此,它会执行它,但 test 没有所需的参数,因此会发生错误。你可以这样:t=/x/; t.test("x");先赋值一个正则表达式对象,然后调用测试方法。

我希望现在能理解我。

【讨论】:

  • 这不能回答我的问题。我的问题是Why? 问题,而不是How can I make this work? 问题。
  • t=/x/.test 或 (t=/x/.test) 你强制分配一个“t”执行正则表达式方法测试”,不带参数。
  • 你确定吗?我认为函数调用需要括号。 f=s=>s+s;g=f;g(2) 正确给出 4 而 f=s=>s+s;g=f() 使 g 成为 NaNg(2) 给出 TypeError
  • 但这是 lambda 函数而不是赋值
  • 我不明白其中的区别,但也许你可以编辑你的答案,通过解释这个来真正解决我的问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多