ECMAScript with 语句

有标签的语句

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

它的语法:

with (expression) statement

例如:

var sMessage = "hello";
with(sMessage) {
  alert(toUpperCase());    //输出 "HELLO"
}

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

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

 

for……in

<html>
<body>
<script type="text/javascript">
var x
var mycars = new Array()
mycars[0] = "宝马"
mycars[1] = "奔驰"
mycars[2] = "宾利"

for (x in mycars)
{
document.write(mycars[x] + "<br />")
}
</script>
</body>
</html>

关键字 this

this 的功能

在 ECMAScript 中,要掌握的最重要的概念之一是关键字 this 的用法,它用在对象的方法中。关键字 this 总是指向调用该方法的对象,例如:

var oCar = new Object;
oCar.color = "red";
oCar.showColor = function() {
  alert(this.color);
};

oCar.showColor();        //输出 "red"

在上面的代码中,关键字 this 用在对象的 showColor() 方法中。在此环境中,this 等于 oCar。下面的代码与上面的代码的功能相同:

var oCar = new Object;
oCar.color = "red";
oCar.showColor = function() {
  alert(oCar.color);
};

oCar.showColor();        //输出 "red"

使用 this 的原因

为什么使用 this 呢?因为在实例化对象时,总是不能确定开发者会使用什么样的变量名。使用 this,即可在任何多个地方重用同一个函数。请思考下面的例子:

function showColor() {
  alert(this.color);
};

var oCar1 = new Object;
oCar1.color = "red";
oCar1.showColor = showColor;

var oCar2 = new Object;
oCar2.color = "blue";
oCar2.showColor = showColor;

oCar1.showColor();        //输出 "red"
oCar2.showColor();        //输出 "blue"