ECMAScript語句之with 語句

ECMAScript with 語句,用於設置代碼在特定對象中的作用域(with運行緩慢,設置了屬性值時更加緩慢,最好避免使用with語句)

一、with 語句用於字符串(配合toUpperCase()方法)

var a = "CGLweb前端";
with(a) {
console.log(toUpperCase()); //輸出 "CGLweb前端"
}

二、with 語句可以方便地用來引用某個特定對象中已有的屬性,但是不能用來給對象添加屬性。要給對象創建新的屬性,必須明確地引用該對象

function xinxi() {
this.name = "青格勒";
this.age = "28";
this.gender = "男";
}
var people=new xinxi();
with(people)
{
var str = "姓名: " + name;
str += "、年齡:" + age;
str += "、性別:" + gender;
console.log(str);
}

三、with語句中的對象不是作爲執行環境添加到作用域中,而是執行環境之中作用的

var obj1 = [
{a: 11},
{c: 12}
];
function cgl() {(www.gendna5.com)
var a = 2;
with (obj1) {
{a = 3};
{c = 4};
}
console.log(a); //3
console.log(c); //4
console.log(obj1); //[ { a: 11 }, { c: 12 } ]
console.log(obj1[0].a); //11
console.log(obj1[1].c); //12
}
cgl();
console.log(obj1[0].a); //11
console.log(obj1[1].c); //12

這個因爲資料有限就說道這裏吧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章