• 【JS如何实现继承?】



    在JavaScript中,可以通过以下方式实现继承:

    原型链继承

    1. 原型链继承:利用原型链实现继承,通过将子类的原型指向父类实例来继承父类的属性和方法。示例代码如下:
    function Parent() {
      this.name = 'Parent';
    }
    Parent.prototype.sayHello = function() {
      console.log('Hello, I am ' + this.name);
    }
    
    function Child() {}
    Child.prototype = new Parent();
    
    var child = new Child();
    child.sayHello();  // Hello, I am Parent
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    构造函数继承

    1. 构造函数继承:在子类构造函数中调用父类构造函数,通过apply或call方法继承父类的属性和方法。示例代码如下:
    function Parent(name) {
      this.name = name;
    }
    Parent.prototype.sayHello = function() {
      console.log('Hello, I am ' + this.name);
    }
    
    function Child(name, age) {
      Parent.call(this, name);  // 调用父类构造函数
      this.age = age;
    }
    
    var child = new Child('Child', 10);
    child.sayHello();  // Error: child.sayHello is not a function
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    组合继承

    1. 组合继承:结合原型链继承和构造函数继承,既继承了父类原型上的属性和方法,又继承了父类构造函数中的属性和方法。示例代码如下:
    function Parent(name) {
      this.name = name;
    }
    Parent.prototype.sayHello = function() {
      console.log('Hello, I am ' + this.name);
    }
    
    function Child(name, age) {
      Parent.call(this, name);  // 调用父类构造函数
      this.age = age;
    }
    Child.prototype = new Parent();  // 继承父类的原型
    
    var child = new Child('Child', 10);
    child.sayHello();  // Hello, I am Child
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    寄生组合继承

    1. 寄生组合继承:在组合继承的基础上,通过一个空函数来避免调用两次父类构造函数。示例代码如下:
    function Parent(name) {
      this.name = name;
    }
    Parent.prototype.sayHello = function() {
      console.log('Hello, I am ' + this.name);
    }
    
    function Child(name, age) {
      Parent.call(this, name);  // 调用父类构造函数
      this.age = age;
    }
    
    function inheritPrototype(child, parent) {
      var prototype = Object.create(parent.prototype);  // 创建父类原型的副本
      prototype.constructor = child;  // 修正副本的constructor
      child.prototype = prototype;  // 将修正后的副本赋值给子类原型
    }
    inheritPrototype(Child, Parent);  // 继承父类原型
    
    var child = new Child('Child', 10);
    child.sayHello();  // Hello, I am Child
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
  • 相关阅读:
    深度学习求解微分方程系列二:PINN求解burger方程
    JavaWeb
    解决SpringBoot 中Controller层加入RequestMapping导致HTML页面的静态文件路径变化问题
    如何保证Redis和MySQL两者之间数据的一致性
    1024节日
    【云原生 | Kubernetes 系列】---Prometheus Blackbox_exporter监控
    【一】Spring Cloud 系列简介
    人工智能驱动的自然语言处理:解锁文本数据的价值
    云原生 | Docker - [Dockerfile]
    [附源码]java毕业设计个性化新闻推荐系统
  • 原文地址:https://blog.csdn.net/Ge_Daye/article/details/133584934