js的with語句使用方法

來源:互聯網
上載者:User

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

2)文法格式
with(object instance)
{
//代碼塊
}
有時候,我在一個程式碼中,多次需要使用某對象的屬性或方法,照以前的寫法,都是通過:對象.屬性或者對象.方法這樣的方式來分別獲得該對象的屬性和方法,著實有點麻煩,學習了with語句後,可以通過類似如下的方式來實現:
with(objInstance)
{
var str = 屬性1;
.....
} 去除了多次寫對象名的麻煩。

3)舉例
<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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.