結合了prototype和call的組合繼承

js是基於面向對象的語言,要實現繼承至關於要把子類加入父類的原型鏈。就實現了繼承。  經過prototype和call,apply來實現
 
組合繼承:
function Parent(age ){
  this.age = age 
}
Parent.prototype.run = function(){
 return `age is ${this.age}`
}

function Child(age){
  Parent.call(this,age)   //對象冒充,  (第2次調用Parent)
}

Child.prototype = new Parent();   // 原型連接繼承,   (第一次調用Parent)


var test = new Child(20);
console.log(test.run())

上面寫法 有個小問題是: Parent會調用2次 javascript

改進 : 實現組合式繼承的時候,Child.prototype = Object.create(Parent.prototype)java

function Parent(age ){
  this.age = age 
  console.log('執行');
}
Parent.prototype.run = function(){
 return `age is ${this.age}`
}

function Child(age){
  Parent.call(this,age)   
}

Child.prototype = Object.create(Parent.prototype);   


var test = new Child(20);
console.log(test.run())


//測試下:     
Child.prototype.__proto__ ===Parent.prototype     //true 完美實現,而且只執行一次Parent

 

構造函數內部的方法 和它原型對象上的方法區別:app

  • 定義在構造函數內部的方法,會在它的每個實例上,都克隆這個方法;
  • 定義在構造函數prototype屬性上的方法,會讓它的全部實例都共享這個方法,可是不會在每一個實例內部,從新定義這個方法。
  • 若是咱們的應用須要建立不少的對象,而且這些對象還有許多的方法,爲了節省內存,咱們建議把這些方法都定義在構造函數的prototype屬性上。

結合實際需求 看狀況使用了。函數

相關文章
相關標籤/搜索