LoginSignup
0
0

More than 5 years have passed since last update.

Javascriptのevalの評価の仕方

Last updated at Posted at 2017-08-26

変数の代入

<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>
0
0
0

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
0
0