深入认识javascript中的eval函数[转载] - 疯子的紫梦's 学习窝
JavaScript 字符串转换数字

深入认识javascript中的eval函数[转载]

疯子的紫梦 posted @ 2010年2月19日 06:05 in JavaScript , 995 阅读

发现为本文起一个合适的标题还不是那么容易,呵呵,所以在此先说明下本文的两个目的:
(1)介绍javascript中的eval函数的用法
(2)如何在函数内执行全局代码

 

►先来说eval的用法,内容比较简单,熟悉的可以跳过。
eval函数接收一个参数s,如果s不是字符串,则直接返回s。否则执行s语句。如果s语句执行结果是一个值,则返回此值,否则返回undefined。
需要特别注意的是对象声明语法“{}”并不能返回一个值,需要用括号括起来才会返回值,简单示例如下:
var code1='"a" + 2';    //表达式
var code2='{a:2}';      
//语句
alert(eval(code1));     
//->'a2'
alert(eval(code2));     
//->undefined
alert(eval('(' + code2 + ')'));    //->[object Object]
        可以看到,对于对象声明语句来说,仅仅是执行,并不能返回值。为了返回常用的“{}”这样的对象声明语句,必须用括号括住,以将其转换为表达式,才能返回其值。这也是使用JSON来进行Ajax开发的基本原理之一。在例子中可以清楚的看到,第二个alert语句输出的是undefined,而第三个加了括号后输出的是语句表示的对象。
            ►现在来说本文的重点,如何在函数内执行全局代码。为了说明这个问题,先看一个例子:
var s='global';    //定义一个全局变量
function demo1(){
    eval('var s="local"');
}
demo1();
alert(s);    //->global
         很好理解,上面的demo1函数等价于:function demo1(){var s='local';},其中定义了一个局部变量s。
        所以最后的输出是global并不是什么奇怪的事情,毕竟大家都能很清楚的区分局部变量和全局变量。
        仔细体会一下,可以发现eval函数的特点,它总是在调用它的上下文变量空间(也称为:包,closure)内执行,无论是变量定义还是函数定义都是如此,所以如下的代码会产生函数未定义的错误:
var s='function test(){return 1;}';     //一个函数定义语句
function demo2(){
    eval(s);
}
demo2();
alert(test());    //->error:test is not defined
        这是因为test函数在局部空间定义,demo2函数内可以访问到,外面就访问不到了。

         而在实际的Ajax开发中,有时我们需要从服务器动态获取代码来执行,以减轻一次载入代码过多的问题,或者是一些代码是通过Javascript自身生成的,希望用eval函数来使其执行。
但这样的动态获取代码的工作一般在函数内完成,比如:
function loadCode(){
    var code=getCode();
    eval(code);
}
       可见eval不可能在全局空间内执行,这就给开发带来了不少问题,也看到过很多人为此郁闷。
        不过现在偶终于找到了解决办法,嘿嘿,可以同时兼容IE和Firefox,方法如下:
var X2={}    //my namespace:)
X2.Eval=function(code){
 if(!!(window.attachEvent && !window.opera)){
  
//ie
  execScript(code); 
 }else{
  
//not ie
  window.eval(code);
 }
}
        现在如果要想在函数内定义全局代码,就可以通过调用X2.Eval(code)方法,一个例子如下:
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孰是孰非也就很难说了,大家知道解决办法就好。

 

Avatar_small
NCERT Gk Sample Pape 说:
2022年9月26日 01:07

Subject experts have provided the latest version of NCERT GK Sample Paper 2023 Class 10 that’s supports for all formats of exams such as SA1, SA2, FA1, FA2, FA3, FA4 and Assignments conducting under Term-1 & Term-2 of the course. Candidates download the practice question bank with important questions from where which questions have asked repeatedly in the past years old exams, NCERT Gk Sample Paper Class 10 How they indirectly ask the questions and so on by follow those NCERT STD-10 GK Model Papers 2023.Subject experts have provided the latest version of NCERT GK Sample Paper 2023 Class 10 that’s supports for all formats of exams such as SA1, SA2, FA1, FA2, FA3, FA4 and Assignments conducting under Term-1 & Term-2 of the course.

Avatar_small
Meghalaya 6th Class 说:
2023年7月19日 22:10

Students Should Download the Respective Stream wise MBOSE Board 6th Class Exam Syllabus Subjects of Hindi, English, Mathematics, Science, Social Science etc, Pdf Format Provide Check the same From our page here,Students need to Start Their Preparation by first Downloading the Stream wise MBOSE 6th Class Curriculum Syllabus 2024 Latest Edition.Meghalaya Board Class Syllabus 2024 is Designed in Meghalaya 6th Class Syllabus 2024 Accordance with the NCERT Based Guidelines and helps Students to get an Overview of the Hindi, English Medium All Subject, MBOSE keeps a Class Exam Pattern with the aim to Provide a Quality Education for All Students, On the basis of the Current Educational Demands


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter