Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

10.实现原型链继承、借用构造函数继承、组合继承 #10

Open
gumingWu opened this issue Jun 2, 2022 · 1 comment
Open

Comments

@gumingWu
Copy link
Owner

gumingWu commented Jun 2, 2022

红宝书第六章
羽哥写的继承镇楼

原型链继承的基本思想

利用原型,让一个引用类型继承另一个引用类型的属性和方法

题目:请写出原型链继承的示例,举例原型链继承的优缺点,使用原型链继承的场景

__

借用构造函数继承的基本思想

借用构造函数继承也叫做(伪造对象或经典继承),思想就是在子类型构造函数的内部调用超类型的构造函数

题目:请写出构造函数继承的示例,举例构造函数继承的优缺点,使用构造函数继承的场景

__

组合继承的基本思想

组合继承就是原型链继承+借用构造函数继承

题目:请写出组合继承的示例,举例组合继承的优缺点,使用组合继承的场景

@LuMMao
Copy link

LuMMao commented Jun 4, 2022

原型链继承

优点:

  1. 继承父类属性
  2. 可继承父类原型上的属性和方法

缺点:

  1. 引用类型的属性被所有实例共享
  2. 在创建子类实例时,无法向父类传参
  3. Child.prototype 的 constructor 属性被重写
  4. 给子类原型添加属性和方法必须在替换原型之后

场景:

  1. Vue2.0 中处理数组响应
  2. Vue2.0 的 extend

例子:

function Parent() {
  this.name = 'parent'
  this.names = ['parent1', 'parent2']
}
Parent.prototype.getName = function () {
  console.log(this.name);
}

function Child() { }
Child.prototype = new Parent();
var child1 = new Child();
var child2 = new Child();
child1.getName();
child1.names.push('parent3')
console.log(child1.names, child2.names);

构造函数继承

优点:

  1. 避免了引用类型被所有实例共享
  2. 子类可向父类传参

缺点:

  1. 方法都在构造函数中定义,每次创建实例都会创建一遍方法
  2. 无法访问父类原型上的属性和方法

场景:

  1. 基于一个需要提前做一些处理的方法去创建另一个方法方法

例子:

function Parent(name) {
  this.name = name;
  this.names = ['parent1', 'parent2']
}
function Child(name) {
  Parent.call(this, name);
}
var child1 = new Child('child1');
var child2 = new Child();
child1.names.push('parent3');
console.log(child1.names, child2.names, child1.name);

组合继承

优点:

  1. 可继承父类自身及其原型链上的属性和方法
  2. 子类可向父类传参
  3. 避免了引用类型共享

缺点:

  1. 调用了两次父类构造函数

场景:

  • 实在想不到了~~

例子:

function Parent(name) {
  this.name = name;
  this.names = ['parent1', 'parent2']
}
Parent.prototype.getName = function () {
  console.log(this.name);
}
function Child(name) {
  Parent.call(this, name);
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child1 = new Child('child1')
var child2 = new Child('child2');
child1.names.push('parent3')
child1.getName();
console.log(child1.names, child2.names, child1.name, child2.name);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants