關於繼承

繼承前提---- 繼承分爲兩種:類與類之間的繼承,類創造實例對象bash

funtion parent(){
    //私有屬性
    var name ;
    //私有方法
    var addName = function(){};
    //公有屬性
    this.sex;
    //公有方法
    this.addSex = function(){};
}
parent.prototype = {
    //共有屬性(原型屬性)
    age: 11,
    //共有方法
    setAge: function(){}
}複製代碼

一、類式繼承:(類與類之間的繼承)函數

function parent(){     this.name = [];
}
parent.prototype = {
      age: 12
}

//聲明子類
function child(){}
child.prototype = new parent();
//缺陷:
//一、父類的公共屬性爲引用類型時,子類生成的實例對象之間的屬性會相互影響
let child_example1 = new child();
let child_example2 = new child();
console.log(child_example1.name);//[]
console.log(child_example2.name);//[]
child_example1.name.push(1);
console.log(child_example2.name);//[1]
//二、子類實例沒法初始化父類原型中的屬性和方法

複製代碼

二、構造函數繼承:(類與類之間的繼承)ui

function parent(name){
    this.name = name;
}
parent.prototype = {
    sex: '男'
}
function child(){
    parent.call(this,'ltp');
}
let child_example = new child();
console.log(child.prototype.name);
console.log(child_example.sex);//undefained
console.log(child_example.name);//'ltp'
//缺陷:子類的實例對象和子類沒法訪問父類原型中的屬性和方法
複製代碼

三、組合繼承(類式繼承和構造函數繼承結合)this

function parent(){
    this.name = 'ltp';
}
parent.prototype = {
    age: 11
}
function child(){
    parent.call(this);
}
child.prototype = new parent();
//彌補了構造函數繼承和類式繼承的缺點複製代碼

四、寄生式繼承spa

let origin = {};
function inherit(origin){
   function F(){}
    //方法借用
    F.prototype = origin;
    return new F();
}
let parent = inherit(origin);複製代碼

五、組合寄生prototype

function interit(target,origin){
    function F(){}
    F.prototype = new origin();
    F.constractor = target;
    target.prototype = new F();
}

複製代碼

六、ES6繼承code

class A {
    constructor(name){
        this.name = name;
    }
}
class B extends A {
    constructor(sex,name){
        super(name);
        this.sex = sex;
        this.method1 = this.method1.bind(this);
    }
    method1 () {
        console.log('已繼承');
    }
}
let a = new A('ltp');
console.log(a);
let b = new B('ltp','男');
console.log(b);
b.method1();複製代碼

super()指向父類,能夠向父類實現傳參,constructor是構造方法對象

在ES6繼承中,類沒有私有變量和私有方法,可經過new實現對類的實例化,extends實現類與類之間的繼承繼承

相關文章
相關標籤/搜索