一、构造函数继承
改变this指向继承
只能继承构造函数中this身上的属性和方法,不能继承原型身上的属性和方法
三种方法:
1、.call(this);
2、.apply(this);
3、.bind(this,n)();
function Parent(n){
this.num = n;
this.show = function(){
console.log(this.num);
}
}
Parent.prototype.init = function(){
console.log(123);
}
function Child(n){
Parent.bind(this,n)();
}
var p = new Parent(3.1415);
p.show();
p.init();
var c = new Child(520);
c.show();
二、原型对象继承
只能继承原型身上的属性和方法,不能继承构造函数中this的属性和方法
原型是一个对象,直接将原型作为一个对象复制,注意对象的深浅拷贝
// for(var i in Parent.prototype){
Child.prototype[i] = Parent.prototype[i];
}
//遍历进行深拷贝
function Parent(n){
this.num = 123;
this.show = function(){
console.log(this.num);
}
}
Parent.prototype.init = function(){
console.log("hello");
}
function Child(n){}
for(var i in Parent.prototype){
Child.prototype[i] = Parent.prototype[i];
}
Child.prototype.init = function(){
console.log("html");
}
var p = new Parent(3.1415);
p.init();
console.log(p.num);
var c = new Child(520);
c.init();
console.log(c.num);
三、原型继承–原型链
既能继承原型的属性和方法,又能继承构造函数的属性和方法
缺点:不方便传参
function Parent(n){
this.num = n;
}
Parent.prototype.init = function(){
console.log("hello");
}
function Child(n){}
Child.prototype = new Parent(520);
Child.prototype.init = function(){
console.log("html");
}
var p = new Parent(3.1415);
p.init();
console.log(p.num);
var c = new Child();
c.init();
console.log(c.num);
console.log(p);
console.log(c);
四、混合继承
混合继承 : 常用的继承方式之一
构造函数继承 + 原型对象继承
function Parent(n){
this.num = n;
}
Parent.prototype.init = function(){
console.log("hello");
}
function Child(n){
Parent.call(this,n)
}
for(var i in Parent.prototype){
Child.prototype[i] = Parent.prototype;
}
Child.prototype.init = function(){
console.log("html");
}
var p = new Parent(3.1415);
p.init();
console.log(p.num);
var c = new Child(123);
c.init();
console.log(c.num);
五、es6的继承
原理:封装改变this指向继承和原型链继承
优点:方便简单
缺点:没有普遍浏览器的支持
class Parent{
constructor(n){
this.name = n;
}
show(){
console.log(this.name + "执行了show");
}
}
class Child extends Parent{
constructor(n){
super(n);
}
show(){
console.log(123);
}
}
var p = new Parent("zhangsan");
p.show();
var c = new Child("lisi");
c.show();