javascript ()でeval ()およびfunction ()


ねえ、今日のブログで、簡単に話し合いますeval() and Function() JavaScriptで.
始めましょう.

ブリーフ

eval() and Function() JavaScriptの2つの強力なツールは、両方の文字列としていずれかに渡されたJavaScript式を評価することができます.彼らは両方とも同じものに使用されます、しかし、彼らがあなたの表現を扱う方法において異なりますが.
始めましょうeval() .

eval ()

eval() JavaScript式を文字列として受け取り、それを実行するグローバル関数です.それ以外は何も返しませんundefined . あなたのHTMLと使用にスクリプトを書くならばeval() , ノードのような環境では、出力をコンソールに出力していることに気づくでしょうconsole.log() . これは、例えば、式の結果を標準出力または等価にパイプする傾向があるからです.
例を挙げましょう.あなたがユーザーがいくつかの値を入力し、アプリがコンソールに結果を出力しているアプリを書くと言う.トリッキーな権利?eval() あなたの時間を節約できます.ちょうどユーザーがevalに入力し、魔法を聞かせ.
let userInput = "2+4";
eval(userInput); // output : 6

function ()


evalの代わりにFunction() . eval ()と同じように、結果を直接出力するのではなく、実行のための文字列としていくつかの式をとります.eval ()へのより高速で安全な代替手段です.上記と同じ例を試してみましょうFunction() .
let userInput = "2+4";
let result = Function(userInput);
あなたが上記の結果を記録しようとするならば、あなたは得ます
function anonymous() {
        2+4
}
なぜそう?これはFunction() 匿名関数を返します.もっと見ると、文字列を通過した表現が関数本体にあることがわかります.
文字列内のreturn文を追加する場合はどうすればよいですか?
let userInput = "2+4";
let result = Function("return " + userInput); // which is same as "return 2+4"
もう一度ログ出力結果を試してください.これを得る
function anonymous() {
        return 2+4
}
我々は、我々が現在我々の算術演算の結果を返すことに気がつきます.しかし、現在、我々は実際の価値が欲しいです.この関数を実行することでこれを得ることができます.
let userInput = "2+4";
let result = Function("return " + userInput)(); // which is same as "return 2+4"
あなたが結果を記録してコンソールを調べるならば、我々は6を得るのに気付きます.

ノート


大きな力が大きな責任をeval() and Function() JavaScriptで手に持っている本当に強力なツールです.しかし、その力は価格で来る.任意のコードは、技術的な十分なユーザーや悪意のある個人によって実行することができます.eval() 特に危険です.これはeval() . いくつかのコードを評価し、結果をユーザーのマシンに格納するアプリケーションを作成して、ブラウザでfileapiを使用します.利用可能eval() あなたのアプリに対して、悪意のあるタスクを実行するFileAPIへのアクセスを取得します.
再び.eval() よりずっと遅いFunction() .
引用する

eval() is also slower than the alternatives, since it has to invoke the JavaScript interpreter, while many other constructs are optimized by modern JS engines.

Additionally, modern javascript interpreters convert javascript to machine code. This means that any concept of variable naming gets obliterated. Thus, any use of eval() will force the browser to do long expensive variable name lookups to figure out where the variable exists in the machine code and set its value. Additionally, new things can be introduced to that variable through eval() such as changing the type of that variable, forcing the browser to re-evaluate all of the generated machine code to compensate.


詳しく知るeval and Function
ビデオを好む?