代码之家  ›  专栏  ›  技术社区  ›  John McCollum

javascript中的“with”关键字[重复]

  •  43
  • John McCollum  · 技术社区  · 15 年前

    可能重复:
    Are there legitimate uses for JavaScript’s “with” statement?

    我最近发现,在javascript中,可以执行如下操作:

    with document{
        write('foo');
        body.scrollTop = x;
    }
    

    其缺点是需要检查每个变量是否属于document对象,从而产生大量开销。

    或者,可以这样做:

    var d = document;
    d.write('foo');
    d.body.scrollTop = x;
    

    是否存在使用“with”关键字是正当的情况?

    4 回复  |  直到 8 年前
        1
  •  16
  •   Annie    15 年前

    下面是一些支持with关键字的博客文章。但请阅读阿扎祖尔发布的yui博客文章!

    http://webreflection.blogspot.com/2009/12/with-worlds-most-misunderstood.html http://webreflection.blogspot.com/2009/12/with-some-good-example.html

        2
  •  62
  •   gnat Nat Poor    8 年前

    别用它: http://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/

    JavaScript的 with 语句的目的是提供一个速记法,用于编写对对象的重复访问。所以不是写作

    ooo.eee.oo.ah_ah.ting.tang.walla.walla.bing = true;
    ooo.eee.oo.ah_ah.ting.tang.walla.walla.bang = true;
    

    你可以写

    with (ooo.eee.oo.ah_ah.ting.tang.walla.walla) {
        bing = true;
        bang = true;
    }
    

    看起来好多了。除了一件事。你不可能通过查看代码来判断 bing bang 会被修改的。威尔 ooo.eee.oo.ah_ah.ting.tang.walla.walla 被修改?或者全局变量 发巨响 被揍了?不可能确定…

    如果你不能阅读一个程序并确信你知道它将要做什么,你就不能确信它将正确工作。因为这个原因, 具有 声明应该避免…

        3
  •  14
  •   Rich    15 年前

    尽管到处都有相反的建议,但我认为“with”还是有其用处的。例如,我正在为javascript开发一个域模型框架,它使用下划线字符的方式与jquery使用“$”的方式基本相同。这意味着如果没有“with”,我的代码中会有很多下划线,这些下划线会使代码的可读性降低。下面是使用框架的应用程序的随机行:

    _.People().sort(_.score(_.isa(_.Parent)),'Surname','Forename');
    

    而用“with”看起来就像

    with (_) {
        ...
    
        People().sort(score(isa(Parent)),'Surname','Forename');
    
        ...
    }
    

    真正有用的是“with”的只读版本。

        4
  •  5
  •   Community CDub    7 年前

    我会避免在生产代码中使用它,因为它是不明确的,但是有一个替代的解决方案,通过使用 with 模仿 let 绑定,这是我之前的答案:

    使用for循环内的函数替代标准闭包解决方案:

    <a  href="#">blah</a><br>
    <a  href="#">blah</a><br>
    <a  href="#">foo</a><br>
    <script>
        (function() {
        var anchors = document.getElementsByTagName('a');
            for ( var i = anchors.length; i--; ) {
                var link = anchors[i];
                with ({ number: i }) {
                    link.onclick = function() {
                        alert(number);
                    };
                }
            }
        })();
    </script>
    

    学分 nlogax 因为我提供了一个解决方案: Javascript infamous Loop issue?

    这是标准溶液:

    <script>
        (function() {
        var anchors = document.getElementsByTagName('a');
        for ( var i = anchors.length; i--; ) {
            var link = anchors[i];
            (function(i) {
                link.onclick = function() {
                    alert(i)
                }
            })(i);
        }
        })();
    </script>