JavaScript基礎-物件導向編程<2>

來源:互聯網
上載者:User

標籤:

2.動態添加,修改和刪除對象屬性和方法

例如:用類Object()建立一個Null 物件user,然後修改其行為。

(1) 添加屬性

var user=new Object(); //建立一個沒有屬性和方法的Null 物件user.name="jack"; //添加屬性nameuser.age=21; //添加屬性ageuser.sex="male"

若輸出結果,可用alert(user.name)等語句進行顯示。

(2)添加方法

針對前面的Null 物件user,添加一個方法 alert():

user.alert=function(){        alert("my name is:"+this.name);  }

調用:user.alert(); //可顯示其名字為jack

(3)修改屬性和方法

修改就是用新屬性替換舊屬性。

例如:

user.name="tom";user.alert=function(){      alert("hello,"+this.name); //這時的方法中name屬性已經已經替換為tom}

若用彈出對話方塊顯示其內容,user.alert()值為 "hello,tom"。

(4)刪除屬性和方法

其實,刪除屬性或方法就是將其值定義為undefined,即

user.name=undefined;user.alert=undefined;

3.使用大括弧文法建立無類型對象

其文法為:

{    property1:statement,    property2:statement,    .......,    propertyN:statementN}

這裡通過使用大括弧,使多個屬性或方法成為一個組,實現對象的定義。

 樣本 :使用大括弧文法建立一對象

<script language="javascript" type="text/javascript">   var obj={ }; //定義一個Null 物件, 等同於 var obj=new Object();   var user={           name:"jack", //定義name屬性並賦初值           favoriteColor:["red","green","black"], //定義顏色數組           hello:function(){ //定義方法                    alert("hello"+this.name);              },           sex:"male"   }      user.hello(); //調用方法</script> 

4.prototype對象

每個函數其實也是一個對象,它們對應的類是 function. 它們具有特殊的身份,每個函數對象都具有一個子物件prototype,即prototype表示了該函數的原型。而函數也是

類,prototype就是表示了一個類的成員集合。

 既然 protoype是一個對象,也可以動態地對其屬性和方法進行修改

 例如:

function class1(){     // 空函數}class1.protoype.method=function(){ // 增加方法                    alert("it‘s a text method");}    var obj1 =new class1();    obj1.method; //調用對象方法

 

JavaScript基礎-物件導向編程<2>

聯繫我們

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