with() {} 的用法

var use = "other";  
var katana = {  
isSharp: true,  
use: function(){  
this.isSharp = !!this.isSharp;  
}  
};  
with ( katana ) {  
//assert( true, "You can still call outside methods." );  
  
isSharp = false;  
use();  
alert(use!='other');//true  
alert(this);//window Object  
//assert( use != "other", "Use is a function, from the katana object." );  
//assert( this != katana, "this isn't changed - it keeps its original value" );  
}  
alert(typeof isSharp);//undefined  
alert(katana.isSharp);//false  

1.在with(){}语句中,你可以直接使用with指定的对象的变量和方法。

2.如果外部存在和with指定的对象的变量同名的属性,那么with指定对象中的属性会覆盖其他同名的属性。

3.this指定的是katana的外部作用域。

4.在with语句中只能使用和更改对象已有属性,不能为对象添加新的属性

5.如果为对象添加新的属性,新添加的属性会作为全局对象的属性,而不是with指定对象的属性。

6.私有数据和共有数据是的定义是不一样的

7.由于使用with(this){}使得访问共有数据和私有数据是一样的

8.方法的的定义和变量的定义相似,共有方法必须使用this前缀,但是访问共有方法的时候和私有方法是一样的,由于使用with(this){}

原文地址:https://www.cnblogs.com/shuaishuaidejun/p/7427517.html