如何将"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

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

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

编辑

使用callbind方法。

// Call Approach
var func = /o/.test;
func.call(/o/, "hello")
//Bind Approach
var func = /o/.test.bind(/o/);
func("hello");

最新更新