標籤:
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>