继承
子类继承父类的属性和方法
-
原型继承
让父类中的属性和方法在子类的实例的原型链上
-
let child = new Child();
-
child.prototype = new Parent();
-
child.prototype.constructor = Child;
特点:
- 不像其他语言中的集成一样,(其他语言的继承是拷贝继承,就是子类继承父类的时候,会把父类中的属性和方法拷贝一份,供子类的实例来调用), 它是把父类的原型放到子类实例的原型上,实例想调取这些方法,是基于proto原型查找机制完成
- 子类可以重写父类的方法,(这样会影响其他实例)
- 父类中的私有或者共有属性方法,最后变为子类中共有属性和方法
-
function A(x) {
this.x = x;
}
A.prototype.getX = function() {
console.log(this.x);
}
function B(y) {
this.y = y;
}
B.prototype.getY = function() {
console.log(this.y);
}
let b1 = new B(100);
b1.prototype.constructor = B;
b1.y;
b1.getY();
- call继承
call继承的特点:
原理: child把parent当做普通函数执行,让parent中的this指向child实例
相当于给child的实例设置很多私有的属性或者方法
- 只能继承父类私有的属性或者方法 (将parent当做普通函数执行,并且将parent执行环境设为当前child实例,所以只能继承父类私有的属性或者方法,和父类有原型上的属性和方法没有关系)
- 父类私有变为子类私有
function A(x) {
this.x = x;
}
A.prototype.getX = function(){
console.log(this.x);
}
function B(y) {
// 借用类A的构造函数
// A(200);
// 在new执行B函数的时候this代表B的实例
A.call(this,200);
this.y = y;
}
B.prototype.getY = function(){
console.log(this.y);
}
let b1 = new B(100);
- 寄生组合继承
寄生组合继承: call继承 + 类似于原型继承
特点: 父类私有和公有的分别是子类实例的私有和共有属性方法
function A(x) {
this.x = x;
}
A.prototype.getX = function(){
console.log(this.x);
}
function B(y) {
// 借用类A的构造函数
// A(200);
// 在new执行B函数的时候this代表B的实例
A.call(this,200);
this.y = y;
}
// 创建一个对象,让空对象的__proto__指向A.prototype
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
B.prototype.getY = function(){
console.log(this.y);
}
let b1 = new B(100);
// 实现Object.create方法
Object.create = function(obj) {
// let oo = {};
// oo.__proto__ = obj;
// return oo;
// 在IE下不兼容
function Fn() {};
Fn.prototype = obj;
return new Fn();
}
- ES6中继承
ES6中的类不能够当做普通函数执行
class A {
constructor(x) {
this.x = x;
}
getX(){
return this.x;
}
}
class B extends A {
constructor(x,y) {
super(x);
this.y = y;
}
getY() {
return this.y;
}
}