感谢所有的想法,我最终只是在构建脚本中做文本替换,输出JS,基本上用eval代替$ EVAL $,所有东西都被压缩后。我希望纯粹的JS方式,但有这么多不同的eval浏览器实现,它可能会更好地离开eval独自
但基于Dimitar的答案和一些摆弄,这是我发现。 好像之所以这样[“的eval”]没有工作是因为,它的发生,在MooTools的JSON.decode的地方,也是一个内部的哈希:
var JSON = new Hash({
// snip snip
decode: function(string, secure){
if ($type(string) != 'string' || !string.length) return null;
if (secure && !(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) return null;
return this.eval('(' + string + ')'); // Firefox says: TypeError: this.eval is not a function
}
});
但是,如果我存储“顶级”本地范围(所有的代码,包括mootools的,匿名函数中运行),那么它的工作原理:
var TOP = this;
var JSON = new Hash({
// snip snip
decode: function(string, secure){
if ($type(string) != 'string' || !string.length) return null;
if (secure && !(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) return null;
return TOP.eval('(' + string + ')'); // All good, things run within the desired scope.
}
});
然而,这并不在Safari工作,所以底线是,我试图做不能做到交叉兼容。 eval是一种特殊的敏感功能,每个浏览器都以不同的方式对待它。
因为'eval'不被认为是一种普通的功能,你可能会胜过YUI压缩器,但是你会遇到浏览器,它们不会或很快不会让你用任何其他名称调用'eval'。 – 2010-02-03 23:29:35