JS中的繼承

阿龍丶along發表於2018-07-05

在js中,es6之前是沒有類的,類的概念是從es6開始提出來的. 所以JS中的繼承應該理解為原型鏈繼承.

js的繼承就是由原型鏈作為實現繼承的主要方法. 每一個建構函式都擁有一個原型物件,基本思想就是利用原型讓一個引用型別繼承另一個引用型別的屬性和方法.或者說,js中的一個子類別繼承自父類別,便使得子類具有了父類的各種屬性和方法.

JS繼承的方式

分別說一下經典的prototype 繼承,和 ES6的class繼承.

1. 原型鏈繼承

JS中的繼承
基本原理就是將一個建構函式的原型物件賦值給另一個的例項

 function Parent(name){
     this.name=name
     this.genter='男'
 }
 //宣告一個原型鏈上面的屬性
 Parent.prototype.sayname=function(){
     console.log('你的身份是'+this.name)
     
 }
 function Child(name){
     this.name=name
 }
 
 Child.prototype=new Parent('爸爸')//這裡就是繼承了Parent的屬性方法
 
 var child=new Child('兒子')
 
 child.sayname() //'你的身份是兒子'
複製程式碼

2. 類式繼承

  function Parent(name){
     this.name=name
 }
 
 Parent.prototype.sayname=function(){
     console.log('你的身份是'+this.name)
 }
 function Child(name){
     Parent.call(this,name)
 }
 Child.prototype.__proto__=Parent.prototype  //這一句就實現了繼承,Child擁有了sayname方法
 var child=new Child('寶寶')
 console.log(child)
複製程式碼

缺點:會繼承父類的一些不必要的屬性,比如說genter屬性,我們不需要知道.

解決方法:

f=function(){}
f.prototype=Parent.prototype
Child.prototype=new f()
複製程式碼

es6 的寫法

class Parent {
    constructor(name){
        this.name=name
    }
    sayname(){
        console.log('你的身份是'+this.name)
    }
}

class Child extends Parent{
    constructor(name){
        super(name)
    }
    get age(){
        return '21'
    }
}
var child =new Child('寶寶')
child.sayname()//你的身份是寶寶
複製程式碼

缺點:不能在child.prototype上定義非函式的屬性,

比如child.age 用傳統ES5寫法可以寫為age:"21"在class 中只能用函式return出來.

相關文章