javascript - 如何将 `RegExp.test` 部分应用于字符串?

标签 javascript binding method-call

为什么这不起作用:

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/

相关文章:

javascript - 将现有的 HTML 和 CSS 文件链接到 Meteor 元素

javascript - 在javascript中在变量内部传递变量

javascript - 有没有办法用 AngularJS 创建自定义动画事件

ios - 使用来自另一个类方法的参数调用类方法

java - 为什么我收到此错误,该错误指示该方法必须返回float类型的值

javascript - ReactJS + Webpack : Why Uncaught Error: Cannot find module "../media/interiorTest.jpg"?

ios - Swift 中的可选绑定(bind)在prepareForSegue 中不起作用

c# - 如何在 ItemsControl 中绑定(bind) DataTemplate

c# - WPF MVVM : TextBox needing format and Button with IsDefault set to True

java对多个对象的方法调用