eval(fn) and eval(arrowFn) returns different value

前端 未结 4 870
小鲜肉
小鲜肉 2021-01-26 09:13

As per the Mozilla docs in order to execute a function using eval it must be wrapped inside ( ) i.e. if you don\'t use them then it treate

4条回答
  •  灰色年华
    2021-01-26 09:34

    First of all, EcmaScript is the "official" name for JavaScript. Now that ES2015 is finalised, it effectively just becomes JavaScript v6 to most people. So, this difference does not come from the different engin.

    The origin of the different behavior comes from the result of the string which is written in the eval function. the result of the first eval string is a function definition and there is not anything to return. On the other side, the second eval is evaluating a lambda function, so the result of the eval is that function. To clear this concept, you can rewrite the code like the following:

    var fn = "function a(){ return 1;}";
    var es6fn = "()=>{}";
    
    console.log(eval(fn)); // undefined
    console.log(eval(es6fn)); // ()=>{}
    console.log(typeof eval(es6fn)); // ()=>{} i.e. a function
    console.log(a()); // call the a() function

    As, you can see, the a() is defined as a function, and you can use the function after the first eval. So, the first eval is run and all back to the return value for eval function.

提交回复
热议问题