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

2018-03-27 14:04:20 +08:00
 china521
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);
};
1764 次点击
所在节点    问与答
6 条回复
china521
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
2018-03-27 14:33:03 +08:00
为什么要用 with、eval 呢?
china521
2018-03-27 14:40:14 +08:00
@lrz0lrz 可以理解为一个沙盒系统,实际中得用到。比如每段代码执行的时候,变量值不一样
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
2018-03-28 12:19:28 +08:00
@blackywkl 是的,with 进去的函数不能被里面的 eval 重定义,一重定义好像会改变当前 eval 的作用域到第一次定义的地方,就出现了这种错误,好像是 safari 的 BUG
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.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/441782

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX