首页 > 解决方案 > 如何将“RegExp.test”部分应用于字符串?

问题描述

为什么这不起作用:

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

标签: javascriptbindingmethod-call

解决方案


当您从 Object 获取方法并将其分配给变量时,您需要提供绑定,this因为上下文( Object )没有与方法一起传递。

var func = /o/.test.bind(/o/);
console.log( func("hello") );


推荐阅读