js構(gòu)造函數(shù)的繼承

js構(gòu)造函數(shù)的繼承

1call()

(1) call()可以調(diào)用函數(shù)
(2) call()可以修改this的指向,使用call()的時候 參數(shù)一是修改后的this指向,參數(shù)2,參數(shù)3..使用逗號隔開連接

 function fn(x, y) {
     console.log(this);
     console.log(x + y);
}
  var xhc = {
    name: 'andy'
  };
  fn.call(xhc, 1, 2);//調(diào)用了函數(shù)此時的this指向了對象xhc,

2子構(gòu)造函數(shù)繼承父構(gòu)造函數(shù)中的屬性

  1. 先定義一個父構(gòu)造函數(shù).
  2. 再定義一個子構(gòu)造函數(shù)
  3. 子構(gòu)造函數(shù)繼承父構(gòu)造函數(shù)的屬性(使用call方法)
 // 1. 父構(gòu)造函數(shù)
 function Father(uname, age) {
   // this 指向父構(gòu)造函數(shù)的對象實例
   this.uname = uname;
   this.age = age;
 }
  // 2 .子構(gòu)造函數(shù) 
function Son(uname, age, score) {
  // this 指向子構(gòu)造函數(shù)的對象實例
  // 3.使用call方式實現(xiàn)子繼承父的屬性
  Father.call(this, uname, age);
  this.score = score;
}
var son = new Son('kunkun', 18, 100);
console.log(son);

3借用原型對象繼承方法 (組合繼承)

  1. 先定義一個父構(gòu)造函數(shù)
  2. 再定義一個子構(gòu)造函數(shù)
  3. 子構(gòu)造函數(shù)繼承父構(gòu)造函數(shù)的屬性(使用call方法)
// 1. 父構(gòu)造函數(shù)
function Father(uname, age) {
  // this 指向父構(gòu)造函數(shù)的對象實例
  this.uname = uname;
  this.age = age;
}
Father.prototype.money = function() {
  console.log(1111111);
 };
 // 2 .子構(gòu)造函數(shù) 
  function Son(uname, age, score) {
      // this 指向子構(gòu)造函數(shù)的對象實例
      Father.call(this, uname, age);
      this.score = score;
  }
// Son.prototype = Father.prototype;  這樣直接賦值會有問題,如果修改了子原型對象,父原型對象也會跟著一起變化
  Son.prototype = new Father();
  // 如果利用對象的形式修改了原型對象,別忘了利用constructor 指回原來的構(gòu)造函數(shù)
  Son.prototype.constructor = Son;
  // 這個是子構(gòu)造函數(shù)專門的方法
  Son.prototype.exam = function() {
    console.log(2222222);

  }
  var son = new Son('kunkun', 18, 100);
  console.log(son);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容