js中的with语句

来源:互联网 发布:淘宝牛肉丸哪个牌子好 编辑:程序博客网 时间:2024/05/18 06:00

语法结构:

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语句现在已经不推荐使用了,例如在严格模式下是被禁用的。

function foo(){ ‘use strict’;with ({});}

SyntaxError: Strict mode code may not include a with statement

那么如何让避免使用with语句呢?

要避免这样的代码:

with(foo.bar.baz){
console.log('hello '+first+' '+last)
}

你可以使用一个临时变量来代替:

var b=foo.bar.baz;
console.log('hello '+b.first+' '+b.last)

如果你不想再当前作用于中引入临时变量,你可以用IFEE

(function(){
var b=foo.bar.baz;
console.log('hello '+b.first+' '+b.last)
}())

你也可以把要访问的参数作为一个选项传入IFEE

(function(b){
console.log('hello '+b.first+' '+b.last)
}(foo.bar.baz))

那么说到这里,很多同学就会问为什么废弃with呢:

function logit(msg,opts){
with(opts){
console.log('msg: '+msg);//(1)
}
}
console.log(logit('hello',{}));
console.log(logit('hello',{msg:'world'}))

输出:

msg: hello
如果opts有一个msg属性,那么语句(1)就不会在访问参数msg
msg: world

with语句会产生三种问题

1、性能问题

变量查找变得很慢,因为对象是临时性插入到作用域链中的。

2、代码可能产生不可预期的效果,仅仅通过标识符周围的上下文,你无法预知下一个标识符会指向什么,根据BrendanEich(javascript之父)的说法,这是with废弃的真正原因

3、代码压缩工具不会压缩with中的变量名。


0 0