JS中常見的幾種繼承方法


1.原型鏈繼承

 1 // 1.原型鏈繼承
 2 /* 
 3     缺點:所有屬性被共享,而且不能傳遞參數
 4 */
 5 function Person(name,age){
 6     this.name = name
 7     this.age = age
 8 }
 9 Person.prototype.sayName = () =>{
10     console.log(this.name)
11 }
12 function Man(name){
13     
14 }
15 Man.prototype = new Person()
16 Man.prototype.name = 'zhangsan'
17 var zhangsan = new Man('zhangsan')
18 console.log(zhangsan.name) //zhangsan

2.構造函數繼承(經典繼承)

// 構造函數繼承(經典繼承)
/* 
    優點:可以傳遞參數
    缺點:所有方法都在構造函數內,每次創建對象都會創建對應的方法,大大浪費內存
*/
function Perent(name,age,sex){
    this.name = name
    this.age = age
    this.sex = sex
    this.sayName = function(){
        console.log(this.name)
    }
}

function Child(name,age,sex){
    Perent.call(this,name,age,sex)
}
let child = new Child('lisi' , 18, '男')
console.log(child)   //Child { name: 'lisi', age: 18, sex: '男', sayName: [Function] }

3.組合方式繼承(構造函數 + 原型鏈)

// 3.組合模式(構造函數 + 原型鏈)
/* 
    這種方式充分利用了原型鏈與構造函數各自的優點,是JS中最常用的繼承方法

*/
function Animal(name,age){
    this.name = name
    this.age = age
}
Animal.prototype.sayName = function () {
    console.log(this.name)
}
function Cat(name,age,color){
    Animal.call(this,name,age)
    this.color = color
}
Cat.prototype = Animal.prototype  //將Cat的原型指向Animal的原型
Cat.prototype.constructor = Cat   //將Cat的構造函數指向Cat
let cat = new Cat('xiaobai',3,'white')
console.log(cat) //Cat { name: 'xiaobai', age: 3, color: 'white' }
cat.sayName()   //xiaobai

4.es6方法繼承

// 4.es6繼承方法
class Per {
    constructor(name){
        this.name = name
    }
    sayName(){
        console.log(this.name)
    }
}

class Son extends Per{
    constructor(name,age){
        super(name)
        this.age = age
    }
}
let son = new Son('zhangsan',18)
console.log(son) //Son { name: 'zhangsan', age: 18 }
son.sayName() //zhangsan

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM