var s='global'; function demo3(){ X2.Eval('var s="local"'); } demo3(); alert(s); //->'local'
可见,在demo3函数内重新定义了全局变量s=”local”。 需要注意的是X2.Eval并不返回值,如果要进行表达式的求值,还是用系统的eval函数。X2.Eval设计为仅做全局代码定义用。 其实看到这里,或许有人感觉问题也太容易解决了点,呵呵,但发现这个办法倒是需要些运气和技巧的: (1)对于IE浏览器,默认已经提供了这样的函数:execScript,用于在全局空间执行代码,只是知道的人还不多。 (2)对于Firefox浏览器,直接调用eval函数,则在调用者的空间执行;如果调用 window.eval则在全局空间执行。这个知道的人估计就更少了。毕竟alert(eval==window.eval)返回true! Firefox的eval函数的特点的确是很令人奇怪的,但从javascript规范中倒也能找到其来源: If value of the eval property is used in any way other than a direct call (that is, other than by the explicit use of its name as an Identifier which is the MemberExpression in a CallExpression), or if the eval property is assigned to, an EvalError exception may be thrown. 意思大概就是说eval函数的执行是和调用者相关的,但并没有说其执行上下文的问题。所以IE和Firefox孰是孰非也就很难说了,大家知道解决办法就好。