javascript物件導向思想

來源:互聯網
上載者:User

標籤:

JavaScript 使用函數來定義類。
文法:
function className(){
    // 具體操作
}

function Person() {    this.name=" 張三 ";  // 定義一個屬性 name    this.sex=" 男 ";  // 定義一個屬性 sex    this.say=function(){  // 定義一個方法 say()        document.write("嗨!大家好,我的名字是 " + this.name + " ,性別是 " + this.sex + "。");    }}

在JavaScript中,建立對象(即類的執行個體化)使用 new 關鍵字。

this 關鍵字是指當前的對象。

在JavaScript中,可以使用“ . ”和“ [ ] ”來訪問對象的屬性。只能使用“ . ”來訪問對象的方法。

function Person() {    this.name=" 張三 ";  // 定義一個屬性 name    this.sex=" 男 ";  // 定義一個屬性 sex    this.age=22;  // 定義一個屬性 age    this.say=function(){  // 定義一個方法 say()        return "嗨!大家好,我的名字是 " + this.name + " ,性別是 " + this.sex + ",今年 " + this.age +"歲!";    }}var zhangsan=new Person();alert("姓名:"+zhangsan.name);  // 使用“.”來訪問對象屬性alert("性別:"+zhangsan.sex);alert("年齡:"+zhangsan["age"]);  // 使用“[ ]”來訪問對象屬性alert(zhangsan.say);   // 使用“.”來訪問對象方法

動態添加屬性和方法

// 定義類function Person(name,sex) {    this.name=name;  // 定義一個屬性 name    this.sex=sex;  // 定義一個屬性 sex    this.say=function(){  // 定義一個方法 say()        return "嗨!大家好,我的名字是 " + this.name + " ,性別是 " + this.sex + " 。";    }}// 建立對象var zhangsan=new Person("張三","男");zhangsan.say();// 動態添加屬性和方法zhangsan.tel="029-81892332";zhangsan.run=function(){   return  " 我跑得很快! ";}// 彈出警告框alert("姓名:"+zhangsan.name);alert("姓別:"+zhangsan.sex);alert(zhangsan.say());alert("電話:"+zhangsan.tel);alert(zhangsan.run());

 

javascript物件導向思想

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.