jos*_*736 4 javascript regex v8 node.js
我最近发现,当您在一个 V8 上下文中使用文字正则表达式语法时,instanceof RegExp即使您RegExp在上下文之间共享全局对象,也会返回 false 。
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
");
Run Code Online (Sandbox Code Playgroud)
您如何可靠地检查对象是否是RegExp跨上下文的?
看起来这个建议给了我们最可靠的路线。
if (Object.prototype.toString.call(regExp) == '[object RegExp]') ...
Run Code Online (Sandbox Code Playgroud)
这依赖于 的指定行为toString,即返回对象的 JavaScript 内部[[Class]]属性(加号"[object "和"]")。
由于这是简单的字符串比较,因此它可以跨上下文工作。