【问题标题】:Should I use the "with" statement in generated code?我应该在生成的代码中使用“with”语句吗?
【发布时间】:2011-11-08 14:38:54
【问题描述】:

我正在开发一种编译成javascript的编程语言,生成的代码包含太多重复,比如:

cls.$init = function(){
    this.property1 = {};
    this.anotherProperty = [1, 2, 3, 4];
    this.yetAnotherProperty = "test";
    /* etc */
}

可以使用with 语句将其变得更小(在这种情况下,当初始化许多属性时):

cls.$init = function(){
    with(this){
        property1 = {};
        anotherProperty = [1, 2, 3, 4];
        yetAnotherProperty = "test";
        /* etc */
    }
}

但问题是……我应该在生成的代码中使用with 语句吗? (后面就不修改了)

【问题讨论】:

  • 根据googletechtalks 上的这个视频,它会对你的脚本产生影响

标签: javascript code-generation


【解决方案1】:

with 语句在使用严格模式时将在下一个 ECMAScript 标准中消失,所以我会习惯不使用它。

https://developer.mozilla.org/en/JavaScript/Strict_mode#Simplifying_variable_uses

【讨论】:

  • 您的意思一定是“在 当前 ECMAScript 标准中”,对吧? ;)
  • ECMAScript 5 就是我的意思。 :)
【解决方案2】:

您为什么担心自动生成代码中的重复?在 gzip 压缩时它可能会被压缩掉,并且添加 with 会在运行时产生开销。 Douglas Crockford 也表示它正在消失:http://www.yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/#comment-586082

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    相关资源
    最近更新 更多