V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
china521
V2EX  ›  问与答

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

  •  
  •   china521 · 2018-03-27 14:04:20 +08:00 · 1745 次点击
    这是一个创建于 2193 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2018-03-28 23:07:15 +08:00
    china521
        1
    china521  
    OP
       2018-03-27 14:19:37 +08:00
    ```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  
       2018-03-27 14:33:03 +08:00
    为什么要用 with、eval 呢?
    china521
        3
    china521  
    OP
       2018-03-27 14:40:14 +08:00   ❤️ 1
    @lrz0lrz 可以理解为一个沙盒系统,实际中得用到。比如每段代码执行的时候,变量值不一样
    blackywkl
        4
    blackywkl  
       2018-03-27 16:26:31 +08:00
    @china521 不是不能重复定义的问题啊?

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

    ctx.text 变成 function 了
    china521
        5
    china521  
    OP
       2018-03-28 12:19:28 +08:00
    @blackywkl 是的,with 进去的函数不能被里面的 eval 重定义,一重定义好像会改变当前 eval 的作用域到第一次定义的地方,就出现了这种错误,好像是 safari 的 BUG
    blackywkl
        6
    blackywkl  
       2018-03-28 23:07:15 +08:00
    看了下 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.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1544 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 17:03 · PVG 01:03 · LAX 10:03 · JFK 13:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.