问题描述:

<script type="text/javascript">

var number = "10";

(function(){

alert(number);

alert(eval('number=22'));

})();

var func = function() {

alert (new Function( 'return (' + number + ')' )());

}

func(); // prints 22.

</script>

It first alerts 10, then alerts 22 then why is it alerting 22 again instead of 10. Does eval function overrides my variable in global scope.

网友答案:

No, eval isn't executed in the global scope but you don't have a variable named number in your local scope. So you're changing the global one.

You may see it with this little change :

(function(){
  var number; // this will ensure the global number isn't changed
  alert(number);  // this will print "undefined"
  alert(eval('number=22')); // this won't change the global variable
})();

Note that alert(eval('number=22')); returns the result of the evaluation and number=22 returns 22. That's why the second alert gives 22.

网友答案:

Since you don't have a variable in your local scope, its changing the global one. Try this one below. It would print 100 instead of 22.

<script type="text/javascript">


  var number = 100;

  (function(){
    var number;
    alert(number);    
    alert(eval('number=22'));

  })();

  function func() {
      alert (new Function( 'return (' + number + ')' )());
  }

  func();

</script>
网友答案:

eval is evil

don't use it.

If you remove the use of eval what is happening is maybe more obvious - you are redefining the value of the global variable number inside the first anonymous function:

var number = "10";

(function(){
    number = 22; // this is a reference to the global variable `number`
})();

var func = function() {
    alert (new Function( 'return (' + number + ')' )()); // this is another use of eval - don't do this
}

func(); // prints 22 - expected.
相关阅读:
Top