浅入了解js的几种继承

239 阅读1分钟
  • 1、原型链继承
function a(name){
    this.name=name;
}
a.prototype.getName=function(){
    return this.name
}
function b(){
    console.log(this.name)
}
b.prototype=new a('x');
let c=new b();
console.log(c.name); // x
优缺点:无法传递参数,实例对引用类型属性的修改会影响到其它实例。
  • 2、构造函数继承
function a(name){
    this.name=name;
}
a.prototype.getName=function(){
    return this.name
}
function b(name){
    a.call(this,name);
}
let c=new b('xx');
let c1=new b('xxxx');
console.log(c.name);
console.log(c1.name);
优缺点:可以传递参数,实例对引用类型属性的修改不会相互影响
  • 3、组合继承
集合了1和2的优点。
function a(name){
    this.name=name;
}
a.prototype.getName=function(){
    return this.name
}
function b(name){
    a.call(this,name);
}
b.prototype=new a();
let c1=new b('x');
let c2=new b('xx');
c1.name='xxx'
console.log(c1.name); // xxx
console.log(c2.name); //xx

  • 4、原型式继承
function createObj(obj){
    let newFn=function(){};
    newFn.prototype=obj;
    return new newFn()
}
let a={
    name:'x',
    num:[1,2]
}
let c1=createObj(a);
let c2=createObj(a);
c1.num.push(3)
console.log(c1.num);
console.log(c2.num)
优缺点:不能传递参数,实例对原型属性的修改
会互相影响。
  • 5、寄生式继承
function create(o){
    let res=Object.create(o);
    return res
}
let a={
    name:'x',
    num:[1,2]
};
let c1=create(a);
let c2=cretat(a);
c1.num.push(3);
c2.num.push(4);
console.log(c1.num); // [1,2,3,4]
console.log(c2.num); // [1,2,3,4]
优缺点:每次创建对象都会创建一遍方法。性能浪费。
  • 6、寄生组合式继承
把以上的有点都集合在一起;
function object(obj){
    function F(){};
    F.prototype=obj;
    return new F();
    
}
function parentAndChild(child,parent){
    let prototype=object(parent.prototype);
    prototype.cunstructor=child;
    child.prototype=prototype;
}
function Parent(name){
    this.name=name;
}
Parent.prototype.getName=function(){
    return this.name
}
function Child(){
    Parent.call(this);
}
parentAndChild(Child,Parent);
  • 7、ES6 Class继承

class a {
    constructor(name){
        this.name=name;
    }
    getName(){
        return this.name
    }
}
class b extends a{
    constructor(name){
        super(name);
        this.name=name;
    }
    names() {
        return super.getName();
    }
}
let c= new b('xx');
console.log(c.names())

让我们一起努力吧EveryBody!