为什么这不起作用:
var func = /o/.test;
func("hello");
// VM165:1 Uncaught TypeError: Method RegExp.prototype.test called on incompatible receiver undefined
// at test (<anonymous>)
// at <anonymous>:1:1
// (anonymous) @ VM165:1
但这确实:
/o/.test("hello");
// true
最佳答案
当您从对象中获取方法并将其分配给变量时,您需要为 this
提供绑定(bind),因为上下文(对象)不会随该方法一起传递。
var func = /o/.test.bind(/o/);
console.log( func("hello") );
关于javascript - 如何将 `RegExp.test` 部分应用于字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60267534/