javascript繼承之原型鏈繼承(一)

(一)原型鏈繼承機制

基本思想是利用原型鏈繼承另一個引用類型的屬性和方法

  • 創建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

通過原型鏈實現繼承時,不能使用對象字面量創建原型方法!!!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容