在面向对象过程中,构造和析构是类的两个重要特性,构造函数在对象创建时候调用,析构函数在对象销毁时被调用
构造函数:
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