首先先上一段代碼
function SuperType(name) {
//父函數(shù)的自定義屬性
this.name = name;
this.colors = ["red","orange","black"];
};
SuperType.prototype.sayName = function() {
//父函數(shù)原型中定義的方法
console.log(this.name);
};
//定義子函數(shù)
function SubType (name,age) {
//子函數(shù)繼承父函數(shù)的屬性
//借用構(gòu)造函數(shù)實現(xiàn)對實例屬性的繼承
SuperType.call(this,name);
//子函數(shù)定義自己的屬性
this.age = age;
}
//子函數(shù)繼承父函數(shù)的方法
//通過原型鏈對原型屬性和方法的繼承
SubType.prototype = Object.create(SuperType.prototype);
//下面注釋的這種寫法子類會具有父類實例的方法,不推薦
//SubType.prototype = new SuperType();
SubType.prototype.constructor =SubType;
//自定義子函數(shù)的方法
SubType.prototype.sayAge = function() {
console.log(this.age);
}
//測試
var instance1 = new SubType("LLL","24");
instance1.colors.push("pink");
console.log(instance1.colors);//"red,orange,black,pink"
instance1.sayName;//"LLL"
instance1.sayAge;//"24"
//測試2
var instance2 = new SubType("XXX","25");
console.log(instance2.colors);//"red,orange,black"
instance2.sayName;//"XXX"
instance2.sayAge;//"25"