2016-04-06 JavaScript-with()的用法

简介:

with 语句可以方便地用来引用某个特定对象中已有的属性,但是不能用来给对象添加属性。要给对象创建新的属性,必须明确地引用该对象。
  with(object instance){
  //代码块
  }
  有时候,在一个程序代码中,多次需要使用某对象的属性或方法,照以前的写法,都是通过:对象.属性或者对象.方法这样的方式来分别获得该对象的属性和方法,着实有点麻烦,学习了with语句后,可以通过类似如下的方式来实现:
  with(objInstance){
  var str = 属性1;
  .....
  } 去除了多次写对象名的麻烦。
<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>2016-04-06 JavaScript--with()的用法</title>
  <script type="text/javascript">

  //with()方法
  function tform(thisform){
   with(thisform){
    if(thisform.user.value==null||thisform.user.value==""){
    alert("用户名为空");
    return false;
    }else if(psw.value==null||psw.value==""){
   alert("密码为空");
   return false;
    }else{
      return true;
    }
   }
  }
  </script>
 </head>
 <body>
  <form action="Main.html" onsubmit="return tform(this)" method="post">
  用户:<input type="text"  name="user"/>
  密码:<input type="password" name="psw"/>
  <input type="submit" value="提交"/>
  </form>
 </body>
</html>

posted @ 2016-04-06 11:37  小兵程序猿  阅读(171)  评论(0编辑  收藏  举报