Kasan Blog

js如何实现继承?

1. 在没有class时,使用原型链

把复用的方法放在Parent1的prototype上,

然后用create(Parent1.prototype)以Parent1.prototype作为原型构建一个对象返回。

作为中间对象,隔离开子类原型和父类原型。 然后再把constructor指向Child1

就可以比较完美地完成继承。

function Parent1(name) {
    this.name = name || '俊宇';
    this.play = [1, 2, 3]
    this.ID = '1';
}
Parent1.prototype.xxx = function(any){
    console.log(any+',居然可以')
}

function Child1(name,like) {
    Parent1.call(this,name)
    this.like = like ;
    this.doing = function(something){
        console.log(this.name+'在做:'+something+'I Like:'+like)
    }
}

Child1.prototype = Object.create(Parent1.prototype);
Child1.prototype.constructor = Child1;



let s1 = new Parent1('P1');
let s2 = new Child1('','apple')
let s3 = new Child1('小明','game')
s2.play.push(4)
console.log(s2.play,s3.play)
s2.ID = '2';
console.log(s2.ID,s3.ID)
s2.xxx('嘻嘻')
s3.xxx('哈哈')
s2.xxx = function(something){console.log(something+',改写了')}
s2.xxx('嘻嘻')
s3.xxx('哈哈')
s2.doing('玩游戏')
s3.doing('打篮球')
console.log(s1.constructor)
console.log(s2.constructor)
console.log(s3.constructor)
console.log(s1)
console.log(s2)
console.log(s3)

2.class继承

extends 关键字

直接子类 extends 父类就可以了,函数和值都可以使用访问。

class Parent{
    constructor(name){
       this.name = name || '俊宇';
       this.play = [1, 2, 3];
       this.ID = '1';
    }
    xxx(any){
        console.log(any+',居然可以')
    }
}


class Child extends Parent{
    constructor(name,like){
        super(name);
        this.like = like;
    }
    doing(something){
        console.log(this.name+'在做:'+something+'I Like:'+this.like)
    }
}

let s1 = new Parent('P1');
let s2 = new Child('','apple')
let s3 = new Child('小明','game')
s2.play.push(4)
console.log(s2.play,s3.play)
s2.ID = '2';
console.log(s2.ID,s3.ID)
s2.xxx('嘻嘻')
s3.xxx('哈哈')
s2.xxx = function(something){console.log(something+',改写了')}
s2.xxx('嘻嘻')
s3.xxx('哈哈')
s2.doing('玩游戏')
s3.doing('打篮球')
console.log(s1.constructor)
console.log(s2.constructor)
console.log(s3.constructor)
console.log(s1)
console.log(s2)
console.log(s3)