5

私は最近、1 つの V8 コンテキストでリテラル正規表現構文を使用すると、コンテキスト間でグローバル オブジェクトを共有している場合でも が false を返すことを発見しました。instanceof RegExpRegExp

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クロスコンテキストかどうかを確実に確認するにはどうすればよいですか?

4

2 に答える 2

8

この提案により、最も信頼できるルートが得られるようです。

if (Object.prototype.toString.call(regExp) == '[object RegExp]') ...

これは、オブジェクト (および)の JavaScript 内部[[Class]]プロパティを返すという の指定された動作にtoString依存しています。"[object ""]"

これは単純な文字列比較であるため、コンテキスト全体で機能します。

于 2013-04-02T00:58:10.083 に答える