Javascript 中with的用法

来源:岁月联盟 编辑:exp 时间:2012-08-14

法:with (<对象>) <语句>;

with 语句可以用来引用某个特定的对象中已有的属性,但是不能用来给对象添加属性,要给对象添加属性,还要明确的引用该对象。

例如:

function users(){

    this.name = 'nobody'; this.age = '23';this.gender = 'girl'

}

var people = new users();

    with(people){

    alert(name);

    }

通常用来缩短特定情形下必须写的代码量:

这是一个很明显的例子:

   
x = Math.cos(3 * Math.PI) + Math.sin(Math.LN10);

y = Math.tan(14 * Math.E);

当使用with时就可以写成这样:

   www.2cto.com
with (Math) { x = cos(3 * PI) + sin(LN10); y = tan(14 * E); }

 


作者: Nobodyhi