手写实现继承

2022-04-07  本文已影响0人  泪滴在琴上

这里就只实现两种方法了,ES6之前的寄生组合式继承 和 ES6之后的class继承方式。

    /**
    * es6之前  寄生组合继承 
    */
    {
      function Parent(name) {
        this.name = name
        this.arr = [1, 2, 3]
      }

      Parent.prototype.say = () => {
        console.log('Hi');
      }

      function Child(name, age) {
        Parent.call(this, name)
        this.age = age
      }

      //  核心代码 通过Object.create创建新对象 子类 和 父类就会隔离
      // Object.create:创建一个新对象,使用现有的对象来提供新创建的对象的__proto__ 
      Child.prototype = Object.create(Parent.prototype)
      Child.prototype.constructor = Child
    }
    
    
    
    /**
    *   es6继承 使用关键字class
    */
     {
      class Parent {
        constructor(name) {
          this.name = name
          this.arr = [1, 2, 3]
        }
      }
      class Child extends Parent {
        constructor(name, age) {
          super(name)
          this.age = age
        }
      }
    }

补充一个小知识, ES6的Class继承在通过 Babel 进行转换成ES5代码的时候 使用的就是 寄生组合式继承。
继承的方法有很多,记住上面这两种基本就可以了!

作者:Ali2333
链接:https://juejin.cn/post/7079681931662589960
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

上一篇 下一篇

猜你喜欢

热点阅读