• js组合继承


    JS组合继承(combination inheritance)是一种常用的继承模式,它通过将原型链和构造函数组合使用来实现继承。

    下面是JS组合继承的详细解析和代码示例:

    1. 创建父类(基类)的构造函数
    1. function Parent(name) {
    2. this.name = name;
    3. this.colors = ['red', 'green', 'blue'];
    4. }

    1. 给父类添加原型方法
    1. Parent.prototype.getName = function() {
    2. console.log(this.name);
    3. };

    1. 创建子类的构造函数,并调用父类构造函数
    1. function Child(name, age) {
    2. Parent.call(this, name);
    3. this.age = age;
    4. }

    1. 设置子类的原型为一个父类实例
    Child.prototype = new Parent();
    

    1. 修正子类的构造函数指向
    Child.prototype.constructor = Child;
    

    1. 添加子类的原型方法
    1. Child.prototype.getAge = function() {
    2. console.log(this.age);
    3. };

    1. 创建子类的实例,并调用父类和子类的方法
    1. var child1 = new Child('Alice', 10);
    2. child1.getName(); // 输出:Alice
    3. child1.getAge(); // 输出:10
    4. child1.colors.push('yellow');
    5. console.log(child1.colors); // 输出:['red', 'green', 'blue', 'yellow']
    6. var child2 = new Child('Bob', 20);
    7. child2.getName(); // 输出:Bob
    8. child2.getAge(); // 输出:20
    9. console.log(child2.colors); // 输出:['red', 'green', 'blue']

    在这个例子中,通过组合使用构造函数和原型链实现了继承。构造函数的继承通过在子类的构造函数中调用父类的构造函数来实现,这样就可以在子类的实例中拥有父类的属性。原型链的继承通过将子类的原型对象设置为父类的一个实例,这样就可以在子类的原型链上访问父类的方法。

    需要注意的是,组合继承的缺点是在创建子类实例时调用了两次父类构造函数,一次是在Child.prototype = new Parent()这一步中,另一次是在Child.call(this, name)中。这样会导致子类的原型对象上多了一些不必要的属性,但是通过Object.create()可以解决这个问题。

    总结:JS组合继承是一种常用的继承模式,它通过组合使用构造函数和原型链实现继承。虽然有一些缺点,但是它兼顾了构造函数继承和原型链继承的优点,可以有效地实现继承和方法的重用。

  • 相关阅读:
    springboot+vue 开发记录(九)后端打包部署运行
    dom4j读取xml内容时丢失换行符
    elasticsearch1
    使用RCurl和R来爬虫视频
    React 组件生命周期
    试用了多款报表工具,终于找到了基于.Net 6开发的一个了
    biquad滤波器的设计
    DPVS的定时器
    如何手撸一个自有知识库的RAG系统
    【python海洋专题二十四】南海年平均海流图
  • 原文地址:https://blog.csdn.net/zxcv321zxcv/article/details/139883179