继承
继承:子类去继承父类的公有属性和私有属性
原型继承
function Parent() { // 父类
this.x = 100;
}
Parent.prototype.getX = function () {
return this.x;
}
function Child() { // 子类
this.y = 200;
}
Child.prototype = new Parent; // 让子类的原型指向父类对象
Child.prototype.getY = function () {
return this.y;
}.
// 对于Child来说。它继承了
var c1 = new Child();
console.log(c1.x); // x是继承父的x
console.log(c1.getX()); // getX是继承父的x
console.log(c1.y); // getX是继承父的x
console.log(c1.getY()); //
优点:可以在子类型构造函数中向父类型构造函数添加参数
缺点:和构造函数模式一样的问题,所有的方法都在构造函数中定义,因此就无法做到函数的复用。而且父类型的原型中定义的方法,对于子类型而言也是不可见的。
这种方式是通过在子类型的函数中调用超类型的构造函数来实现的,这一种方法解决了不能向超类型传递参数的缺点,但是它存在的一个问题就是无法实现函数方法的复用,并且超类型原型定义的方法子类型也没有办法访问到
基于以上问题,借用构造函数的技术也是很少单独使用的。
call继承
<script>
// call继承
// 特点:只能继承父的私有属性
// Parent.call(this);
function Parent() { // 父类
this.x = 100;
}
Parent.prototype.getX = function () { // 子类
return this.x;
}
function Child() {
// 1) 让this指向一个空对象
// 2)this.xx = xx;
// 3)返回这个空对象
Parent.call(this);
this.y = 200;
}
var c1 = new Child();
console.log(c1.x);
</script>
缺点:只能继承私有属性
组合式继承
1)Parent.call(this); // 继承父的私有属性
2)Child.prototype =Object.create(Parent.prototype); 子类继承父类的公有属性
function Parent() { // 父类
this.x = 100;
}
Parent.prototype.getX = function () { // 子类
return this.x;
}
function Child() {
Parent.call(this); // 继承父的私有属性
this.y = 200;
}
Child.prototype.constructor = Child; // 手动修改constructor的指向
var c = new Child();
console.log(c.x);
console.log(c.getX())
```
// Child.prototype = Parent.prototype; 不好
// 为什么?如果再你写了Child.prototype.xx = function(){}
// 意味着父中也可以访问xx 说白了 子类可以影响父类
// 想法:把Parent.prototype对象copy一份 让它俩的原型是彼此独立
// Child.prototype = Parent.prototype;
// 为了不影响父类的原型对象 copy一份赋值给了Child.prototype
Child.prototype = Object.create(Parent.prototype);
// 最好手动的修改一个Child原型对象上constructor指向
ES6中的继承
super(); // 类似于前面我们所说的call继承
extends 类似于原型对象 继承公有属性
class Parent{
constructor() {
this.x = 100;
}
getX(){
return this.x;
}
}
class Child extends Parent{
constructor() {
super(); // 类似于前面我们所说的call继承
this.y = 200;
}
getY(){
return this.y
}
}
var child = new Child();
console.log(child.x);
console.log(child.getX());
编写代码时,ES6 class 带来的最明显的两个便利是:
隐藏原型链的拼接过程,将代码的重点放在类型之间的传承
使用 super 来实现更简化、更灵活的多态方法
实际上,ES6 围绕 class 增加了很多新功能,比如继承这件事情上,与之前不同的是:用 class 实现的继承,既包括类实例的继承关系,也包括类本身的继承关系。这里的类其实是特殊的 JavaScript 函数,而在 JavaScript 中,函数是对象的子类型,即函数对象,所以也能够体现出原型继承。
作者:天方夜
链接:https://juejin.im/post/6844903543476846600
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。