坏小仔

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
 1 <script type="text/javascript">
 2 function globalEval(data) {  
 3 data = data.replace(/^\s*|\s*$/g, "");
 4 if (data) {
 5 var head = document.getElementsByTagName("head")[0] ||
 6 document.documentElement,
 7 
 8 script = document.createElement("script");  
 9 script.type = "text/javascript";
10 script.text = data;
11 head.appendChild(script);  
12 head.removeChild(script);  
13 }
14 }
15 window.onload = function() {
16 (function() {
17 globalEval("var test = 5;");
18 })();
19 assert(test === 5, "The code was evaluated globally.");
20 };
21 </script>

We stressed, when discussing the eval() method, that the evaluation executes in the scope
within which eval() is called; proving it with the test of listing 9.1. But frequently, we may
want to evaluate strings of code in the global scope despite the fact that it may not be the
current execution scope.
For example, within some function we may want to execute code in the global scope, as
in:
(function(){
eval("var test = 5;");
})();
assert(test === 5,
"Variable created in global scope"); //fails!
If we expected the variable test to be created in the global scope as a result of the
execution of the immediate function, our test results are discouraging as the test fails.
Because the execution scope of the evaluation is within the immediate function, so is the
variable scope.
A naïve solution would be to change the code to be evaluated to:
eval("window.test = 5;");




posted on 2012-08-22 17:17  坏小仔  阅读(141)  评论(0编辑  收藏  举报