(一)原型鏈繼承機(jī)制
基本思想是利用原型鏈繼承另一個(gè)引用類型的屬性和方法
- 創(chuàng)建Car構(gòu)造函數(shù)
function Car(){
this.color = "黑色";// 汽車基礎(chǔ)顏色
}
Car.prototype.changeColor = function(otherColor){
// 提供更換顏色方法
this.color = otherColor;
}
- 創(chuàng)建Audi構(gòu)造函數(shù)
function Audi(master){
this.master = master;
}
- Audi原型鏈繼承Car
Audi.prototype = new Car();
- 創(chuàng)建Audi原型鏈方法
Audi.prototype.getColor = function(){
return this.color;
}
Audi.prototype.getMessage = function(){
return this.master+"的奧迪顏色是"+this.color;
}
- 實(shí)例繼承測(cè)試
var car1 = new Audi("老王");
console.log(car1.getColor());// 黑色
console.log(car1.getMessage());// 老王的奧迪顏色是黑色
驗(yàn)證原型和實(shí)例之間的關(guān)系
- 第一種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
通過原型鏈實(shí)現(xiàn)繼承時(shí),不能使用對(duì)象字面量創(chuàng)建原型方法!!!