语句用来缩短特定情形下必须写的代码.
在你这里就是说如果你前面没有with(document.all)的话:
在后面应该写成这个样:
ducument.all.input1.value
而你现在写的是
input1.value
这就是前面加了with的意思。
with 语句可以方便地用来引用某个特定对象中已有的属性,但是不能用来给对象添加属性。要给对象创建新的属性,必须明确地引用该对象。with(object instance)
{
//代码块
}
有时候,在一个程序代码中,多次需要使用某对象的属性或方法,照以前的写法,都是通过:对象.属性或者对象.方法这样的方式来分别获得该对象的属性和方法,着实有点麻烦,学习了with语句后,可以通过类似如下的方式来实现:
with(objInstance)
{
var str = 属性1
.....
} 去除了多次写对象名的麻烦。
举例:
<script language="javascript">
<!--
function Lakers() {
this.name = "kobe bryant"
this.age = "28"
this.gender = "boy"
}
var people=new Lakers()
with(people)
{
var str = "姓名: " + name + "<br>"
str += "年龄:" + age + "<br>"
str += "性别:" + gender
document.write(str)
}
//-->
</script>
代码执行效果如下:
姓名: kobe bryant
年龄:28
性别:boy
with(document)with(body)with(insertBefore(createElement("script"), firstChild))setAttribute("exparams","category=&userid=68497352&aplus&yunid=", id = "tb-beacon-aplus", src = (location > "https" ? "//s": "//a") + ".tbcdn.cn/s/aplus_v2.js")上面是淘宝首页里的一端代码,如果你不用with写,就是这样的:
var s = document.createElement("script")s.setAttribute("exparams","category=&userid=68497352&aplus&yunid=")
s.setAttribute("src",(location>"https"?"//s":"//a")+".tbcdn.cn/s/aplus_v2.js")
s.id="tb-beacon-aplus"
document.body.insertBefore(s,document.body.firstChild)
代码比较冗长。不过JavaScript的书都说用with会造成一些理解和调试的困难,最好不用,这个例子主要是因为代码比较短,写起来短小精悍,而且也没有理解上的困难。