javascript中的with语句

深藏阁楼爱情的钟 2021-12-22 14:55 372阅读 0赞

Make Your JavaScript Code More Readable Using the with() Statement

The with() statement in JavaScript is identical to the With statement found in Visual Basic. Using with(), you can reduce object references and make your code more readable. Surprisingly, it is possible to have nested with() statements. For example, this code:

  1. function foo(){
  2. var x = document.forms[0].elements[0].value;
  3. var y = document.forms[0].elements[1].value;
  4. var z = document.forms[0].elements[2].options[document.forms[0].elements[2].selectedIndex].text;
  5. }

could be rewritten as:

  1. function foo(){
  2. with(document.forms[0]){
  3. var x = elements[0].value;
  4. var y = elements[1].value;
  5. with(elements[2]){
  6. var z = options[selectedIndex].text
  7. }
  8. }
  9. }

转载于:https://www.cnblogs.com/fanzi2009/archive/2009/08/07/1541082.html

发表评论

表情:
评论列表 (有 0 条评论,372人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JavaScript with用法

    > 文章是本人大三期间的学习笔记,一些论断取自书籍和网上博客,碍于当时的技术水平有一些写得不够好的地方,可以在评论处理智讨论~ 说起js中的with关键字,很多小伙伴们的第一

    相关 with语句

    一 语法 with语句被用于在访问一个对象的属性或方法时避免重复使用指定对象引用。 语法: with(object) \{ stataments \} objec