一、原型继承:让父类中的属性和方法在子类实例的原型链上
child.prototype = new PARENT()
CHILD.prototype.constructor = CHILD
特点:
1、不像其它语言中的继承一样(其它语言的继承一般是拷贝继承,也就是子类继承父类,会把父类中的属性和方法拷贝一份到子类中,供子类的实例调取使用),它是把父类的原型放到子类实例的原型链上,实例想调取这些方法,是基于__proto__原型链查找机制完成的
2、子类可以重写父类的方法(这样会导致父类其它的实例也会受影响)
3、父类中私有或者共有的属性方法,最后都会变为子类中公有的属性和方法
function A(){
this.x = x;
}
A.prototype.getX = function(){
console.log(this.x)
};
B.prototype = new A(200);
B.prototype.constructor = B;
function B(){
this.y = y;
}
B.prototype.getY = function(){
console.log(this.y)
}
二、CALL继承
child方法中把parent当做普通函数执行,让parent中的this指向child的实例,相当于给child的实例设置了很多私有的属性或者方法
特点1:只能继承父类私有的属性或者方法,因为把parent当做普通函数执行,和其原型上的属性和方法没有关系
2、父类私有变为子类私有的
function A(){
this.x = x;
}
A.prototype.getX = function(){
console.log(this.x)
};
function B(){
A.call(this,200)
this.y = y;
}
B.prototype.getY = function(){
console.log(this.y)
}
三、寄生组合继承 call 继承+ 类似于原型继承
特点:父类私有和公有的分别是子类实例的私有和公有属性方法
Object.create(obj):创建一个空对象,让空对象__proto__指向OBJ
child.prototype = Object.create(parent);
child.prototype.constructor = child;
因为Object.create不兼容手动创建一个和Object.create方法
Object.create = function (obj) {
function Fn(){};
Fn.prototype = obj;
return new Fn();
}
创建类,让类的原型指向obj,然后返回这个类的实例,这个类的实例指向所属类的原型
function A(){
this.x = x;
}
A.prototype.getX = function(){
console.log(this.x)
};
function B(){
A.call(this,200)
this.y = y;
}
// Object.create(obj):创建一个空对象,让空对象__proto__ 指向obj
B.prototype = Object.create(A.prototype)
B.prototype.constructor = B;
B.prototype.getY = function(){
console.log(this.y)
}
四、ES6中的继承
语法:class child extends parent{},原理是寄生组合继承 让b.prototype.__proto__ = A.prototype
ES6中基于class创造出来的类不能当做普通函数执行
class A {
constructor(x){
this.x= x;
}
getx(){
console.log(1)
}
}
class B {
constructor(Y){
// A.call(this,200);//报错
this.Y= Y;
}
getY(){
console.log(1)
}
}
es6中的继承 extends
class B extends A {
constructor(Y){
super(200)==》相当于A.call(this,200)把父类当做普通方法执行,给方法传递参数,让方法中的this是子类的实例;如果不写contructor,浏览器会自己默认创建相当于constructor(..arg){super(...arg)}
this.Y= Y;
};// 子类继承父类,可以不写contructor,但是一旦设置constructor,则contructor中首先要写super()
getY(){
console.log(1)
}
}
B.prototype = Object.create(A.prototype);// 不允许重定向原型的指向