javascript几种继承方式;不看就out啦

338 阅读2分钟

通过继承方式可以分类:

  1. 只继承父类实例上的属性:call继承
  2. 继承父类的公共属性:链式继承Object.setPrototypeof()Object.create()
  3. 同时继承父类的公共属性和实例上的属性:在子类内部调用call,使用Object.create/链式/Object.setPrototypeof()class extends继承

一、只继承父类的实例上的属性

1. call继承

原理:把父类的this指向子类,并且执行 缺点:不能继承公共属性;

//父类
function A(){
    this.type='我是a类';
}
A.prototype.content={name:'我是a的内容呦!'};
//子类
function Q(){
    this.name='我是q啦';
    A.call(this);
}
Q.prototype.content={name:'我是q的内容,,哈哈哈'};
const q=new Q();
console.log(q);

二、继承父类的公共属性

1. 链式继承

原理:利用的是原型链查找机制;

//父类
function A(){
    this.type='我是a啦';
}
A.prototype.content={name:'我是a的内容呦!'};
//子类
function Q(){
    this.name='我是q啦';
}
Q.prototype.content={name:'我是q的内容,,哈哈哈'};
Q.prototype.__proto__=A.prototype;
const q=new Q();
console.log(q);
2. Object.setPrototypeof(es6的写法)

兼容性不太好

//父类
function A(){
    this.type='我是a啦';
}
A.prototype.content={name:'我是a的内容呦!'};
//子类
function Q(){
    this.name='我是q啦';
}
Q.prototype.content={name:'我是q的内容,,哈哈哈'};
Object.setPrototypeOf(Q.prototype,A.prototype);
const q=new Q();
console.log(q);
3. Object.create()

原理:create方法中声明定义个空函数fn;使fn的prototype=传入的参数;返回fn

⚠️注意:q.proto.constructor是A

//父类
function A(){
    this.type='我是a啦';
}
A.prototype.content={name:'我是a的内容呦!'};
//子类
function Q(){
    this.name='我是q啦';
}
Q.prototype.content={name:'我是q的内容,,哈哈哈'};
Q.prototype=Object.create(A.prototype);
//如果单写Q.prototype=Object.create(A.prototype);;
//此时它的constructor是A;
//所以在Object.create的第二个参数constructor指向Q
Q.prototype=Object.create(A.prototype,{contructor:{value:Q}});
const q=new Q();
console.log(q);

三、同时继承父类的公共属性和实例上的属性

1. 在子类内部调用call,使用Object.create/链式/Object.setPrototypeof()
//父类
function A(){
    this.type='我是a类';
}
A.prototype.content={name:'我是a的内容呦!'};
//子类
function Q(){
    this.name='我是q啦';
    A.call(this);
}
Q.prototype.content={name:'我是q的内容,,哈哈哈'};
Q.prototype.__proto__=A.prototype;//这里用Object.create或者Object.setPrototypeof()都可以
const q=new Q();
console.log(q);
2. es6 class extends
class A{
    static a(){
        console.log('我是a,啦啦啦');
    }
    constructor(){
        this.type='a';
    }
    Sing(){
        console.log('我会唱歌!');
    }
}
class Q extends A{
    constructor(){
        super();
    }
}
const q=new Q();
console.log(q);