1.執行個體屬性、執行個體方法與類屬性、類方法
function circle(r){
this.redius = r; //redius屬性執行個體屬性,即該類型的每個執行個體對象都具有copy該屬性
}
circle.PI = 3.14; //P為circle類的一個類屬性,跟執行個體無關
circle.prototype.area = function (){ return circle.PI*this.redius*this.redius }; //area是一個執行個體方法,裡面引用類屬性PI
circle.init = function (){ return new circle(1);}init()為類方法,此方法用於建立一個半徑為1的圓形
執行個體屬性、執行個體方法類試java中的非靜態屬性或函數
類屬性、類方法類似java中的靜態屬性或函數
2.類繼承
動物類:
function animal(){
this.type = "animal";
}
貓類:
function cat (name,age){
this.name = name;
this.age = age;
}
如何讓cat繼承animal類呢?
1.建構函式繫結模式:
function cat(name,age){
animal.call(this,[arguments]) //arguments為傳遞的參數數組,this參數為調用此函數的對象,這裡是cat
this.name = name;
this.age = age;
}
var c = new car('tom',19);
console.log(c.type);
2.原型繼承模式
cat.prototype = new animal();//給cat的原身prototype重新初始化
cat.prototype.constuctor = cat;//上面已經將原身prototype重新賦值,原身prototype的constructor就不存在,所以這裡需要重新指定constructor值,這裡是cat,
否則後面的繼承鏈出問題
var c = new car('tom',19);
console.log(c.type);
總之編程時候要遵守一點如果重新賦值o.prototype的值:
o.prototype={};
接下來務必要給o.prototype.constructor賦值:
o.prototype.constructor = o;