JavaScript

Javascriptのevalの評価の仕方

変数の代入

<html>
<head>
  <script type="text/javascript">
    eval("5 + 5") === 10; //true
    eval("var ninja = 5;");
    console.log(ninja); //5
   </script>
</head>
</html>

scopeの確認

<html>
<head>
  <script type="text/javascript">
    var test = function() {
                 eval("var ninja1 = 5;");
                 console.log(ninja1); //5
               };
    test();
    console.log(ninja1); //scopeが違うのでError
 </script>
</head>
</html>

letで試してみる。

<html>
<head>
  <script type="text/javascript">
    {
      eval("let ninja2 = 5;");
      console.log(ninja2); //Error letでは動かない
    }
    console.log(ninja2); //Error
   </script>
</head>
</html>

globalのscopeに付け替える

<html>
<head>
  <script type="text/javascript">
    function globalEval(data){
      data = data.replace(/^\s*|\s*$/g, "");
      if (data){
        var head = document.getElementsByTagName("head")[0] ||
                   document.documentElement;
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.text = data;
        head.appendChild(script);
        head.removeChild(script);
      }
    }

    window.onload = function() {
      (function(){
        globalEval("var ninja3 = 5;");
      })();
      console.log(ninja3);
    }
   </script>
</head>
</html>

globalのscopeに関数を付け替える

alertも出せる。
document.writeも動く

<html>
<head>
  <script type="text/javascript">
    function globalEval(data){
      data = data.replace(/^\s*|\s*$/g, "");
      if (data){
        var head = document.getElementsByTagName("head")[0] ||
                   document.documentElement;
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.text = data;
        head.appendChild(script);
        head.removeChild(script);
      }
    }

    window.onload = function() {
      var greet = function(){
        alert("hi hi");
        document.write("hello write");
      }
      (function(){
        globalEval("greet();");
      }).call(this);
    }
   </script>
</head>
</html>