ES5模拟ES6class继承

     // ES6继承
     class Human {
        constructor(name) {
          this.name = name;
        }
      }

      class Man extends Human {
        constructor(args) {
          super(args);
        }
        speak() {
          console.log(this.name);
        }
      }
      const jame = new Man("jame");
      jame .speak()


      // ES5继承
      function Human(name) {
        this.name = name;
      }

      function Man(name) {
        Human.call(this, name);
      }

     /**
       1. 这一步不用Child.prototype = Parent.prototype的原因是怕共享内存,修改父类原型对象就会影响子类
       2. 不用Child.prototype = new Parent()的原因是会调用2次父类的构造方法(另一次是call),会存在一份多余的父类实例属性
       3. Object.create是创建了父类原型的副本,与父类原型完全隔离
      */
      Man.prototype = Object.create(Human.prototype);

      Man.prototype.say = function () {
        console.log(this.name);
      };
      // 构造器指向自身
      Man.prototype.contructor = Man;

      const chris = new Man("chris");
      chris.say();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。