繼承

繼承是指一個對象直接使用另一對象的屬性和方法

  • 得到一個類的屬性
  • 得到一個類的方法

一、原型鏈實現(xiàn)繼承

1、定義一個類
function Person(name,sex) {
    this.name=name;
    this.sex=sex;
}
Person.prototype.sayName = function(){
    console.log(this.name)
}
2、獲取屬性

對象屬性的獲取是通過構(gòu)造函數(shù)的執(zhí)行,在一個類中執(zhí)行另一個類的構(gòu)造函數(shù),就可以把屬性賦值到自己內(nèi)部,但需要把環(huán)境改成自己的作用域內(nèi)

function Male(name,age,sex){
    Person.call(this,name,age);
    this.sex=sex;
}
3、獲取方法

類的方法一般定義在prototype里面

需要注意的幾點:
  • 創(chuàng)建新的ptorotype,而不是直接把Person.proto賦值,因為引用關(guān)系,會導致修改子類的proto也修改了父類的prototype

  • 對子類添加方法,必須在修改其prototype之后,在之前會被覆蓋

  • 此刻子類的constructor屬性指向不對,需重新指定

關(guān)于手動指定對象的原型的幾種方法:

  • object.proto={...}
Man.prototype.__proto__ = Person.prototype//不兼容低版本IE
  • 借用new
//原型繼承
function Person(name, age){
  this.name = name
  this.age = age
}
Person.prototype.sayName = function(){
    console.log(this.name)
}
//讓Man 繼承Person
//1、繼承屬性:讓Person在Man里面執(zhí)行一遍
function Man (name, age, sex) {
  Person.call(this, name, age)
  this.sex = sex
}
//2、方法繼承
var xxx = function (){}
xxx.prototype = Person.prototype
Man.prototype = new xxx()
//3、修正constructor
Man.prototype.constructor = Man
var yyy = new Man()
console.dir(yyy)
  • 使用Object.create()
//1、繼承屬性:讓Person在Man里面執(zhí)行一遍
function Man (name, age, sex) {
  Person.call(this, name, age)
  this.sex = sex
}
//2、方法繼承
inherit(Person, Man)
function inherit(superType, subType) {
  var _prototype = Object.create(superType.prototype)
  _prototype.constructor = subType
  subType.prototype = _prototype
}
//3、在繼承函數(shù)之后寫自己的方法,不然會被覆蓋
Man.prototype.saySex = function() {
  console.log(this.sex)
}
var yyy = new Man()
console.dir(yyy)

二、class繼承

class可以通過extends關(guān)鍵字實現(xiàn)繼承,比es5的通過修改原型鏈實現(xiàn)繼承,要清晰和方便。

es5的繼承,實質(zhì)是先創(chuàng)造子類的實例對象this,然后再將父類的方法添加到this上面。

es6的繼承機制完全不同,實質(zhì)是先創(chuàng)造父類的實例對象this(所以必須先調(diào)用super),然后再用子類的構(gòu)造函數(shù)修改this。

class Point {
  constructor(x,y){
    this.x=x;
    this.y=y;
  }
}

class ColorPoint extends Point {
  constructor(x,y,color) {
    super(x,y);//調(diào)用父類的constructor(x, y)
    this.color=color
  }
}
super
  • super作為函數(shù)調(diào)用時,代表父類的構(gòu)造函數(shù)。es6要求,子類的構(gòu)造函數(shù)必須執(zhí)行一次super函數(shù)。
  • 此時,super雖然代表了父類的構(gòu)造函數(shù),但返回的子類的實例
  • super作為函數(shù)時,只能用在子類的構(gòu)造函數(shù)中
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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