js优雅的继承

「寄生组合式继承」subType子 superType父

  function inheritPrototype(subType, superType) {
             创建对象,创建父类原型的一个副本
             var prototype = Object.create(superType.prototype);
             console.log(prototype, 55)
             增强对象,弥补因重写原型而失去的默认的constructor 属性
             prototype.constructor = subType;
             console.log(prototype, 34)
             指定对象,将新创建的对象赋值给子类的原型
             subType.prototype = prototype;
             console.log(prototype, 44)
         }
 
         // 父类初始化实例属性和原型属性
         function Father(name) {
             this.name = name;
             this.colors = ["red", "blue", "green"];
         }
         Father.prototype.sayName = function () {
             alert(this.name);
         };
 
          借用构造函数传递增强子类实例属性(支持传参和避免篡改)
         function Son(name, age) {
             Father.call(this, name);
             this.age = age;
         }
 
          将父类原型指向子类
         inheritPrototype(Son, Father);
 
         新增子类原型属性
         Son.prototype.sayAge = function () {
             alert(this.age);
         }
 
         var demo1 = new Son("TianTian", 21);
         var demo2 = new Son("TianTianUp", 20);
 
         demo1.colors.push("2"); // ["red", "blue", "green", "2"]
         demo2.colors.push("3"); // ["red", "blue", "green", "3"]
         demo2.sayName()
         console.log(demo1) 

Class实现继承👇

 class Rectangle {
             // constructor
             constructor(height, width) {
                 this.height = height;
                 this.width = width;
             }
             // Getter
             get area() {
                 return this.calcArea()
             }
             // Method
             calcArea() {
                 return this.height * this.width;
             }
         }
 
         const rectangle = new Rectangle(40, 20);
         console.log(rectangle.area);
         // 输出 800
         // 继承
         class Square extends Rectangle {
             constructor(len) {
                 // 子类没有this,必须先调用super
                 super(len, len);
 
                 // 如果子类中存在构造函数,则需要在使用“this”之前首先调用 super()。
                 this.name = 'SquareIng';
             }
             get area() {
                 return this.height * this.width;
             }
         }
         const square = new Square(20);
         console.log(square.area); 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值