1. 程式人生 > >javascript面向物件程式設計--建構函式 實現動態構造

javascript面向物件程式設計--建構函式 實現動態構造

在面向物件過程中,構造和析構是類的兩個重要特性,建構函式在物件建立時候呼叫,解構函式在物件銷燬時被呼叫

建構函式:

  function F(x,y){ this.x=x;this.y=y}

  var f=new F(1,2);

 alert(f.constructor==F); //true,說明F是f的建構函式

注意:建構函式一般是沒有return值的,但有些框架會利用return來作操作的,比如jQuery框架

  function F(x,y){ this.x=x;this.y=y return [];}

 var f=new F(1,2);

alert(f.constructor==F); //false,return之後說明F不再是f的建構函式

 f.constructor返回function Array() { [native code] }

動態構造:

利用call()和apply()實現動態構造,更加靈活的進行面向物件開發

function A(x){this.x=x||0;}

function B(x){

     A.call(this.x); //動態構造A

     this.a=[x];

}

function C(x){

     B.call(this.x); //動態構造B

     this.y=funtion(){return this.x}

}

var c=new C(3);

alert(c.y());//3

說明:構造c時呼叫C,執行C先呼叫B,呼叫B之前呼叫A  ,即建構函式A,B,C通過call()關聯在一起

根據動態構造的這種特性,可以  設計類的多型處理:

funtion F(x,y){

     function A(x,y){

             this.add=funtion(){

                   return x+""+y

           }

     }

 function B(x,y){

             this.add=funtion(){

                   return x+y

           }

     }

if(typepf x=="string"||typeof y=="string"){A.call(this,x,y)}else{B.call(this,x,y)}

}

var f1=new F(3,4);alert(f1.add()) //7

var f2=new F("3","4");alert(f2.add()) //34