(一)原型鏈繼承機制
基本思想是利用原型鏈繼承另一個引用類型的屬性和方法
- 創建Car構造函數
function Car(){
this.color = "黑色";// 汽車基礎顏色
}
Car.prototype.changeColor = function(otherColor){
// 提供更換顏色方法
this.color = otherColor;
}
- 創建Audi構造函數
function Audi(master){
this.master = master;
}
- Audi原型鏈繼承Car
Audi.prototype = new Car();
- 創建Audi原型鏈方法
Audi.prototype.getColor = function(){
return this.color;
}
Audi.prototype.getMessage = function(){
return this.master+"的奧迪顏色是"+this.color;
}
- 實例繼承測試
var car1 = new Audi("老王");
console.log(car1.getColor());// 黑色
console.log(car1.getMessage());// 老王的奧迪顏色是黑色
驗證原型和實例之間的關系
- 第一種instanceof
console.log(car1 instanceof Object);// true
console.log(car1 instanceof Car);// true
console.log(car1 instanceof Audi);// true
- 第二種isPrototypeOf
console.log(Object.prototype.isPrototypeOf(car1));// true
console.log(Car.prototype.isPrototypeOf(car1));// true
console.log(Audi.prototype.isPrototypeOf(car1));// true
通過原型鏈實現繼承時,不能使用對象字面量創建原型方法!!!