本文主要介绍实现继承的六种方式及各自的优缺点,依次是
原型链继承 构造函数继承 组合继承 原型式继承 寄生式继承 寄生式组合继承
1、原型链继承
优点:可以复用父类的方法 缺点: 1)引用类型会被子类改变; 2)无法传递参数
// 代码1
function Fa() {
this.name = 'fa'
this.info = {
age: 11
}
}
Fa.prototype.sayName = function () {
console.log(this.name);
}
function Son() {}
Son.prototype = new Fa(); //核心
Son.prototype.constructor = Son; //补上
2、构造函数继承
优点: 1)可以传递参数; 2)引用属性不会被共享; 缺点:子类不能访问父类上的prototype;
function Fa() {
this.name = 'fa'
this.info = {
age: 11
}
}
Fa.prototype.sayName = function () {
console.log(this.name);
}
function Son() {
Fa.call(this) //核心
}
3、组合继承
优点:结合上面两个优点
function Fa() {
this.name = 'fa'
this.info = {
age: 11
}
}
Fa.prototype.sayName = function () {
console.log(this.name);
}
function Son() {
Fa.call(this)
}
Son.prototype = new Fa();
Son.prototype.constructor = Son;
4、原型式继承
优点:可以复用父类的方法 缺点: 1)引用类型会被子类改变; 2)子类申明无法传递参数;
let Fa = {
name: 'Fa',
groups: [1, 2, 3],
sayName: function () {
console.log(this.name);
}
}
let son = Object.create(Fa); // 核心
5、寄生式继承
在4)的基础上,增加了子类的特有方法,优缺点同上;
let Fa = {
name: 'Fa',
groups: [1, 2, 3],
sayName: function () {
console.log(this.name);
}
}
function myCreate(obj) {
let clone = Object.create(obj);
// 自定义新方法
clone.getName = function () {
console.log(this.name + 'haha');
}
return clone;
}
6、寄生式组合继承
就是结合了上面所有的优点,就是class的内部实现
// 核心函数
function inheritPrototype(child, parent) {
let prototype = Object.create(parent.prototype); // 创建对象
prototype.constructor = child; // 增强对象
Child.prototype = prototype; // 赋值对象
}
// 定义父类
function Parent(name) {
this.name = name;
this.friends = ["rose", "lily", "tom"]
}
Parent.prototype.sayName = function () {
console.log(this.name);
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
inheritPrototype(Child, Parent);
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。