javascript - 如何将“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") );
推荐阅读
- sockets - WinSock:服务器未按与客户端发送的相同序列接收数据
- bash - bash脚本-while循环不读取下一行并按预期存储值
- android - NetBeans 中的插件 Android 开发
- node.js - 如何修复ffmpeg中的“找不到moov atom”错误?
- haskell - 将 Maybe 元素列表从 Just [[x1],[x2]] 展平为 Just [x1,x2]
- slack - slack chat.postMessage 与传入的 webhook?
- json - 使用 jq 获取 json 中匹配元素之后/之前的元素
- python-3.x - 如何同步类python3中的所有方法?
- c++ - 在重新声明时添加默认参数使此构造函数成为默认构造函数
- java - java多线程:注释部分保证计数器同步以及为什么