经过继承方式能够分类:javascript
call继承
链式继承
、Object.setPrototypeof()
、Object.create()
在子类内部调用call,使用Object.create/链式/Object.setPrototypeof()
、class extends继承
call继承
原理:把父类的this指向子类,而且执行 缺点:不能继承公共属性;java
//父类
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);
复制代码
链式继承
原理:利用的是原型链查找机制;es6
//父类
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);
复制代码
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);
复制代码
Object.create()
原理:create方法中声明定义个空函数fn;使fn的prototype=传入的参数;返回fnui
⚠️注意:q.proto.constructor是Athis
//父类
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);
复制代码
在子类内部调用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);
复制代码
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);
复制代码