Javascript 如何检查对象是否是跨V8上下文的正则表达式?
我最近发现,当您在一个V8上下文中使用文本正则表达式语法时,Javascript 如何检查对象是否是跨V8上下文的正则表达式?,javascript,regex,node.js,v8,Javascript,Regex,Node.js,V8,我最近发现,当您在一个V8上下文中使用文本正则表达式语法时,instanceof RegExp返回false,即使您在上下文之间共享全局RegExp对象 var Contextify = require('contextify'); var ctx = Contextify({ RegExp:RegExp, app: anExpressApp }); // When you create a new route, Express checks if the argument is an //
instanceof RegExp
返回false,即使您在上下文之间共享全局RegExp
对象
var Contextify = require('contextify');
var ctx = Contextify({ RegExp:RegExp, app: anExpressApp });
// When you create a new route, Express checks if the argument is an
// `instanceof RegExp`, and assumes it is a string if not.
ctx.run("
app.get(new RegExp('...'), function() { ... }); // works because we share the `RegExp` global between contexts
app.get(/.../, function() { ... }); // does not work
");
如何可靠地检查对象是否是跨上下文的RegExp
?它似乎为我们提供了最可靠的路由
if (Object.prototype.toString.call(regExp) == '[object RegExp]') ...
这依赖于,即返回对象的JavaScript内部属性(加上“[object”
和“]”
)
由于这是一个简单的字符串比较,它可以跨上下文工作。我认为这将确认您有一个正则表达式或假装是正则表达式的东西
var Contextify = require('contextify');
var ctx = Contextify({ RegExp:RegExp, app: anExpressApp });
// When you create a new route, Express checks if the argument is an
// `instanceof RegExp`, and assumes it is a string if not.
ctx.run("
app.get(new RegExp('...'), function() { ... }); // works because we share the `RegExp` global between contexts
app.get(/.../, function() { ... }); // does not work
");
function regExLike(o) {
return typeof o==='object' &&
typeof o.global==='boolean' &&
typeof o.test==='function' ;
}
Object.prototype.toString.call(theRegExp)
返回什么?同样使用instanceof
基本类型也是一个长期的错误-在浏览器上下文中,inter-iframe对象会导致相同的问题,所有JavaScript库在几年前都必须解决这个问题。通常,duck类型是最简单的解决方案,但我想这取决于您的应用程序。@Pointy:看起来您正在使用toString
——它在两种上下文中都返回[object RegExp]
。does/yourregex/.constructor.prototype==RegExp。prototype@jermel:没有,出于同样的原因,instanceof
返回false:separate的RegExp
是一个完全不同的RegExp
。