JS中with函数的作用

JavaScript012

JS中with函数的作用,第1张

with 语句用于设置代码在特定对象中的作用域。

它的语法:

with (expression) statement例如:

var sMessage = "hello"

with(sMessage) {

alert(toUpperCase())//输出 "HELLO"

}

在这个例子中,with 语句用于字符串,所以在调用 toUpperCase() 方法时,解释程序将检查该方法是否是本地函数。如果不是,它将检查伪对象 sMessage,看它是否为该对象的方法。然后,alert 输出 "HELLO",因为解释程序找到了字符串 "hello" 的 toUpperCase() 方法。

提示:with 语句是运行缓慢的代码块,尤其是在已设置了属性值时。大多数情况下,如果可能,最好避免使用它。

with(obj){

}

就是js中的一个关键字啊,他的意思就是在大括号中的代码的作用域的最顶层对象就是此对象。

js中代码都是在一个作用域链中执行的,所有的变量都是在作用域链的从上往下开始查找,直到找到此变量。

比如下面两段代码。

alert(location)

var obj = {location:"aaa"}

with(obj) {

alert(location)

}

上面句代码输出的是window.location对象,下面的代码输出的是obj的location属性 aaa

<script type="text/javascript">

function validate_required(field,alerttxt)

{

with (field)

{

if (value==null||value=="")

{alert(alerttxt)return false}

else {return true}

}

}

function validate_form(thisform)

{

with (thisform)

{

if (validate_required(code," 用户名不能为空!")==false)

{code.focus()return false}

if (validate_required(end," 密码不能为空!")==false)

{end.focus()return false}

}

}

</script>