当前位置: 首页 > news >正文

继承的多种方式

在这里插入图片描述

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;
}

相关文章:

  • Taro+Vue 创建微信小程序
  • 蓝桥杯编程题讲解
  • pytorch自动微分
  • 【数学建模】MATLAB快速入门
  • 每日一题——贪心算法
  • c++ 继承类的构造函数
  • Self-Attention流程的代码实现【python】
  • 使用AWS Lambda轻松开启Amazon Rekognition之旅
  • 【STM32单片机_(HAL库)】3-2-3【中断EXTI】【电动车报警器项目】433M无线收发模块实验
  • 使用Virtio Driver实现一个计算阶乘的小程序——QEMU平台
  • Python-数据爬取(爬虫)
  • Ceph篇之利用shell脚本实现批量创建bucket桶
  • 《区块链与监管合规:在创新与规范之间寻求平衡》
  • 单片机大小端模式
  • 100个练习学习Rust!可变性・循环・溢出
  • Nuxt3【项目配置】nuxt.config.ts
  • Spring Cloud全解析:配置中心之springCloudConfig配置存储
  • leetcode 41-50(2024.08.19)
  • 嵌入式软件--模电基础 DAY 2
  • 手撕C++入门基础
  • 《五行令》《攻守占》,2个月后国博见
  • 浙江演艺集团7部作品组团来沪,今夏开启首届上海演出季
  • A股三大股指低收:汽车股领涨,大金融走弱,两市成交近1.1万亿元
  • 淄博一酒店房间内被曝发现摄像头,当地警方已立案调查
  • 贝壳一季度收入增长42%:二手房市场活跃度维持在高位
  • 习近平复信中国丹麦商会负责人