<script> function example () { this.a=this.b=this.c=0 with (this) { a = 1; b = a + 1; c = b + 1; } }var t=new example() alert(t.a);alert(t.b);alert(t.c) </script>
在function里如果你不this.*****指定他是一个属性怎么知道它是一个变量还是一个属性呢?声明一下就好用。毕竟javascript。<script> function example () { var a = "asdf"; this.b = "asdf" with (this) { a = "ds"; b = "ds"; } return a; }alert(example()); var t=new example() alert(t.a); alert(t.b); </script>
除了明确知道对象是有某个属性,那么用with是个好办法。
(我认为好只是可以省变量的定义)
例如:
下面就可以不用定义新的变量了。
with(new Enumerator(document.all))
for(;!atEnd();moveNext())
{
if(item().className.toUpperCase()=="MYELEMENT")
HandleMyElement(item());
}
但是如果对于Object的Expando属性,并且该属性还不一定已经添加到object中
例如:var totali=0;
objs=[{i:4},{i:5},{}];//最后一个i是没有添加的
for(var i=0;i<objs.length;i++)
with(objs[i])
{
totali+=i;//好在for循环中的i就在前面,容易看到有问题.
//如果with引用的对象和使用的属性都是外部的.
//那么就不容易发现错误了。
//这种错误会不小心把全局(或外部)的变量引用上,
//有时还会更改外部的变量的值。使程序发生错误。
}----------------------
with和this没有什么关系.
只是有时想着,如果能像C++那样,在方法内不写this就好了。
不过我觉得JScript那样更好。
起码如果真有this属性和全局变量的名字有冲突,
JScript是没有 ::globalVar 的引用的。
function example(arg){
with(arg){
a=1;
this.b=this.a+1;
this.c=this.b+1;
}
}
而在调用时使用example(this)的方法
还有个要说..
对于不明来历的Object,不要随便用with,..
虽然也没有多少不明来历的Object...
function example ()
{
this.a=this.b=this.c=0
with (this) {
a = 1;
b = a + 1;
c = b + 1;
}
}var t=new example()
alert(t.a);alert(t.b);alert(t.c)
</script>
function example ()
{
var a = "asdf";
this.b = "asdf"
with (this)
{
a = "ds";
b = "ds";
} return a;
}alert(example());
var t=new example()
alert(t.a);
alert(t.b);
</script>