1. 程式人生 > >js實現繼承

js實現繼承

this super() 實現 urn 使用 log -s 創建 復用

js作為一種弱類型語言,繼承也是其較大的功能之一

首先定義一個父類

// 定義一個教師類
function Teacher (name) {
  // 屬性
  this.name = name || ‘Jack‘;
  // 實例方法
  this.study= function(){
    console.log(this.name + ‘正在學習!‘);
  }
}

一:繼承的方式

1,原型鏈繼承:將父類的實例作為子類的原型

function Student(){ 
}
Student.prototype = new Teacher();
Student.prototype.name = ‘john‘;

測試
var student = new Student();
console.log(student.name);

2,構造繼承 (call,apply) 使用父類的構造函數來增強子類的實例,等同於復制父類的實例屬性給子類

function Student(name) {
  Teacher.call(this);
  this.name = name || "Tom"
}

var student = new Student();
console.log(student.name);

3,實例繼承:為父類實例增加新特性作為子類實例返回

function Student(name){
  var instance = new Teacher();
  instance.name = name || ‘Tom‘;
  return instance;
}

// 測試
var student = new Student();
console.log(student.name);

4,拷貝繼承
function Student(name){
  var teacher= new Teacher();
  for(var p in teacher){
    Student.prototype[p] = Teacher[p];
  }
  Student.prototype.name = name || ‘Tom‘;
}

// 測試
var student= new Student();
console.log(student.name);

5,組合繼承 (通過調用父類的構造,繼承父類的屬性並保留傳參的優點,然後通過將父類實例作為子類原型,實現函數復用

function Student(name){
  Teacher.call(this);
  this.name = name || ‘Tom‘;
}
Student.prototype = new Teacher();

// 測試
var student = new Student();
console.log(student.name);

6,寄生組合繼承 通過寄生方式,砍掉父類的實例屬性,這樣,在調用兩次父類的構造的時候,就不會初始化兩次實例方法/屬性,避免的組合繼承的缺點

function Student(name){
  Teacher.call(this);
  this.name = name || ‘Tom‘;
}
(function(){
  // 創建一個沒有實例方法的類
  var Super = function(){};
  Super.prototype = Teacher.prototype;
  //將實例作為子類的原型
  Student.prototype = new Super();
})();

// 測試
var student = new Student();
console.log(student.name);
 
 
 

js實現繼承