JavaScript で単純な REPL (読み取り、評価、印刷、ループ) の実装を作成しています。次のように、コードと呼び出しコンテキストを分離できます。
var sandbox = {
// Allow the input code to use predefined helper functions
// without the preceding use of the this keyword.
helper_fn: function() { alert("foo"); }
};
var func = new Function("with (this) { " + user_inputed_code + " }");
func.call(sandbox);
これで を閉じてuser_inputed_code
、this
リファラーが にsandbox
アクセスし、入力されたコードが にアクセスまたは変更this
した場合に影響を与えsandbox
ます。
しかし、帰属コードが誤って変数割り当ての前にキーワードvar
を付け忘れた場合、グローバル名前空間が汚染されることに気付きました。
これを防ぐ方法はありますか?もしそうなら、どのように(おそらく正規表現?)?これにアプローチするより良い方法はありますか?