继承的多种方式

发布于:2024-08-20 ⋅ 阅读:(203) ⋅ 点赞:(0)

在这里插入图片描述

1. 原型链继承

function Parent() {
  this.name = "xiaohong";
}
Parent.prototype.getName = function () {
  console.log(this.name);
};

function Child() {}

Child.prototype = new Parent();

const child = new Child();
child.getName();
console.log(child.name);

引用类型的属性被所有实例共享

function Parent() {
  this.names = ["xiaohong", "xiaoming"];
}
Parent.prototype.getName = function () {
  console.log(this.names);
};

function Child() {}

Child.prototype = new Parent();

const child1 = new Child();
child1.names.push("xiaozhang");
console.log(child1.names);
const child2 = new Child();
console.log(child2.names);

2. 构造函数

function Parent() {
  this.names = ["xiaohong", "xiaoming"];
}
function Child() {
  Parent.call(this);
}

const child1 = new Child();
child1.names.push("xiaozhang");
console.log(child1.names);

const child2 = new Child();
console.log(child2.names);

优点:
1. 避免了引用类型的属性被所有实例共享
2. 可以向Parent中传参
缺点:
1. 方法都在构造函数中定义,每次创建实例都会创建一遍方法。

3. 组合继承

function Parent(name) {
  this.name = name;
  this.colors = ["red", "blue", "green"];
}

Parent.prototype.getName = function () {
  console.log(this.name);
};

function Child(name) {
  Parent.call(this, name);
}
Child.prototype = new Parent();
const child = new Child("zhangsan");
child.getName();
console.log(child.name);
// 优点:融合原型链继承和构造函数的优点,是 JavaScript 中最常用的继承模式。

4. 原型继承

function createObj(obj) {
  function F() {}
  F.prototype = obj;
  const ex = new F();
  return new F();
}

// 缺点:包含引用类型的属性值始终都会共享相应的值,这点跟原型链继承一样。
// example:
var person = {
  name: "zhangsan",
  friends: ["xiaoming", "xiaohong"],
};

// person1.__proto__ === (new F()).__proto__ === F.protptype === obj
var person1 = createObj(person);
person1.friends.push("xiaoshuai");
var person2 = createObj(person);
console.log(person1.friends, person2.friends); // [ 'xiaoming', 'xiaohong', 'xiaoshuai' ]  [ 'xiaoming', 'xiaohong', 'xiaoshuai' ]

// console.log(person1.friends, person2.friends);

5. 寄生式继承

// 创建一个仅用于封装继承过程的函数,该函数在内部以某种形式来做增强对象,最后返回对象。
function createObj(o) {
  var clone = Object.create(o);
  clone.sayName = function () {
    console.log("hi");
  };
  return clone;
}