china521
V2EX  ›  问与答

同样的代码,很简单几行没用 safari 失败, chrome 与其它浏览器正常, 请问前端大牛,是不是 safari 解释器的问题

  •  
  •   china521 · Mar 27, 2018 · 2411 views
    This topic created in 3000 days ago, the information mentioned may be changed or developed.
    var ctx = {"test":function(){document.write('ok');}}
    var s = `
    // test 不能重定义, 重定义 safari 就出错 ReferenceError: Can't find variable: main
        function test() {
        }
        function main() {
            test();
        }
        main();
    `;
    with(ctx) {
        eval(s);
    };
    
    6 replies    2018-03-28 23:07:15 +08:00
    china521
        1
    china521  
    OP
       Mar 27, 2018
    ```var ctx = {"foo":function(){}}

    var s = `
    // 不能重定以任何 ctx 里定义过的函数
    function foo() {
    }
    function bar() {
    }
    bar();
    `;
    with(ctx) {
    try{
    eval(s);
    }catch(err) {
    document.write(err);
    }
    };
    ```

    更简单的代码, safari 出错,chrome 正常
    lrz0lrz
        2
    lrz0lrz  
       Mar 27, 2018
    为什么要用 with、eval 呢?
    china521
        3
    china521  
    OP
       Mar 27, 2018   ❤️ 1
    @lrz0lrz 可以理解为一个沙盒系统,实际中得用到。比如每段代码执行的时候,变量值不一样
    blackywkl
        4
    blackywkl  
       Mar 27, 2018
    @china521 不是不能重复定义的问题啊?

    ```
    var ctx = {"test":12313}
    var s = 'function test() {}'
    with(ctx) {
    eval(s);
    };
    ```

    ctx.text 变成 function 了
    china521
        5
    china521  
    OP
       Mar 28, 2018
    @blackywkl 是的,with 进去的函数不能被里面的 eval 重定义,一重定义好像会改变当前 eval 的作用域到第一次定义的地方,就出现了这种错误,好像是 safari 的 BUG
    blackywkl
        6
    blackywkl  
       Mar 28, 2018
    看了下 with 在 MDN 的定义,感觉 safari 是对的???

    If an unqualified name used in the body matches a property in the scope chain, then the name is bound to the property and the object containing the property. Otherwise a ReferenceError is thrown.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3022 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 06:40 · PVG 14:40 · LAX 23:40 · JFK 02:40
    ♥ Do have faith in what you're doing.