首页 > 代码库 > javaScript_with用法

javaScript_with用法

with语句用途

  暂时改变作用域链、简化代码。

语法结构

with(object){    //其他语句}

例1

with(person){       name= "zhang";       address.country= "中国";       sex. = "男";}

对应的常规写法是:

person.name = "zhang";person.address.country = "中国";person.sex= "男";

 

with语句中的优先级

  With语句内变量、方法>object对象内变量、方法>全局变量、方法

例2

function a(){     console.log("function_global");   }var b = ‘variable_global‘;var ob = new Object();ob.a = function(){    console.log("function_object");}ob.b = ‘variable_object‘;with(ob){    var a = function(){        console.log("function_local");    }    var  b = ‘variable_local‘;    a();    console.log(b);}

结果:

 

测试链接:

  http://jsfiddle.net/9dnrgjkg/

 

例3

function a(){     console.log("function_global");   }var b = ‘variable_global‘;var ob = new Object();ob.a = function(){    console.log("function_object");}ob.b = ‘variable_object‘;with(ob){    a();    console.log(b);}

结果:

 测试链接:

  http://jsfiddle.net/9dnrgjkg/1/

 

例4

function a(){     console.log("function_global");   }var b = ‘variable_global‘;var ob = new Object();with(ob){    a();    console.log(b);}

结果:

 测试链接:

  http://jsfiddle.net/9dnrgjkg/2/

 

替代with语句

  执行with语句时,每次需检测with语句中的变量是否属于with包含的对象,因此with语句执行效率不高。为了提高执行效率,建议尽量少使用with语句,可参考例5代替with语句:

例5

var  person = new Object();person .name = "lzhang";person .address.country = "中国";person .sex = "男";

 

javaScript_with用法