LoginSignup
28
27

More than 5 years have passed since last update.

evalを使わずに任意のコード文字列を実行する方法です。

デモ: http://jsdo.it/butchi/akBS

my_eval.js
function myEval(expr) {
  Function(expr)();
}

myEval("alert('Thanks,'); alert('world!');");

これを応用して、Math以下にある関数をメソッド名の記述だけで実行できるコードがこんな感じで書けます。

math_eval.js
function mathEval(expr) {
  return Function('return Math.' + expr);
}

var f = mathEval("pow(2, 10);");
var result = f();
console.log(result);

ちなみに先ほどのコード、特に何にもバリデートしてないので、以下のように実行した場合あぶないです。

mathEval("pow(2, 10), alert('あぶない!')")();

evalを使わない方法だから安全!てわけではなく、あくまでもコード文字列を引数としてクロージャを作れるという程度のものです。

たぶん以下のコードと全く同じです(たぶん)。

wrapped_eval.js
function wrappedEval(expr) {
  (function() {
    eval(expr);
  })();
}

wrappedEval("alert('Thanks,'); alert('world!');");

匿名関数を短い書き方で作る方法という程度に憶えておけばいいと思います。

28
27
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
27