原型链中继承的方法有 call继承,组合继承寄,生组合继承, ES6中的Class类和继承
原型链继承
// 原型链继承
function Arr(a){
this.x = x
this.seyHello = function(){
console.log("3333")
}
}
Arr.prototype.getX =function(){
console.log(this.x)
}
function Bdd(x,y){
this.y = y
}
Bdd.prototype = Object.create(Arr.prototype)
Bdd.prototype.constructor = Bdd
Bdd.prototype.getY = function(){
console.log(this.y)
}
let bb = new Bdd(999)
bb.x
b.getX()
console.log(Arr)
console.log(Bdd);
实现思路:重写原型对象,用一个新的类型的实例去替代
注意:1.默认的原型所有的引用类型都默认继承Object,这个继承也是通过原型链实现的
2.原型链的问题
a.对象实例共享所有继承的属性和方法
b.创建子类型的实例的时候,不能传递参数
组合继承
function Arr(a){
this.x = x
this.seyHello = function(){
console.log("3333")
}
}
Arr.prototype.getX =function(){
console.log(this.x)
}
function Bdd(x,y){
this.y = y
Arr.call(this,x)
}
Bdd.prototype = new A();
Bdd.prototype.constructor = B;
Bdd.prototype.getY = function () {
console.log(this.y);
}
let b = new Bdd(200, 100);
console.log(b);
实现思路:使用原型链实现对原型属性和方法的继承,通过借用构造函数来实现对实例属性的继承
注意:组合继承避免了原型链和借用构造函数的缺陷,融合了他们的优点,成为js中最常用的继承方式。
call继承
function a(){
this.name = function(){
alert("123");
}
}
function b(){
a.call(this); //这里的this代表b对象本身
}
var b = b();
b.name(); //b对象调用了父类a中的方法,实现继承
call继承原理:使b对象继承a对象,那么b对象拥有a对象所有的内容,也可以调用a对象中的方法
寄生组合继承
function Arr(a){
this.x = x
this.seyHello = function(){
console.log("3333")
}
}
Arr.prototype.getX =function(){
console.log(this.x)
}
function Bdd(x,y){
this.y = y
}
Bdd.prototype = Object.create(Arr.prototype)
Bdd.prototype.constructor = Bdd
Bdd.prototype.getY = function(){
console.log(this.y)
}
let bb = new Bdd(200,100)
console.log(Bdd);
实现思路:借用构造函数来继承属性,通过原型链的混成形式来继承方法
注意:高效率只调用了一次构造函数,集寄生式继承和组合继承的优点于一身,是实现基于类型继承的最有效方式
class继承
1 class Point {
2 constructor(x, y) {
3 this.x = x;
4 this.y = y;
5 }
6 }
7
8 class ColorPoint extends Point {
9 constructor(x, y, color) {
10 this.color = color; // ReferenceError
11 super(x, y);
12 this.color = color; // 正确
13 }
14 }
ES6中的class可以看作是一个语法糖,它的绝大部分功能,ES5都可以做到,新的class写法只是让对象原型的写法更加清晰,更加面向对象编程的语法。