您好,欢迎来到易妖游戏网。
搜索
您的当前位置:首页js-实现继承的三种方式

js-实现继承的三种方式

来源:易妖游戏网

继承

js中的继承是通过原型实现的。

方式一:将原型指向继承对象的原型
  function Animal(name) {
        this.name =name;
    }
    Animal.prototype.age = 23;
    let a = new Animal('lily');
    function People(name) {
        this.name = name
    }
    People.prototype = Animal.prototype; // 指定原型对象为Animal 的原型
    let p1 = new People('张三');
    console.log(p1.age) // expect output 23  p1继承了age
    /***
    * 这样做引起一个问题,当修改通过p1 修改Person的原型时,同时也修改了Animal的原型
    **/
    p1.__proto__.age = 48;
    console.log(a.age)  // expect output 48   Animal 的原型被修改了

方式二: 指定原型对象为继承对象的一个实例

  function Animal(name) {
        this.name =name;
    }
    Animal.prototype.age = 23;
    let a = new Animal('lily');
    function People(name) {
        this.name = name
    }
    People.prototype = new Animal('dog'); // 继承Animal
    let p2 = new People('wangermazi'); 
    p2.__proto__.age = 15;
    console.log(a.age) // expect output 23
    console.log(p2.age); // expect output 15
    /*
    * 解决了方式一存在的问题,同时方法三也能解决方式一存在的问题
    ***/

方式三:使用中转函数

   function Animal(name) {
        this.name =name;
    }
    Animal.prototype.age = 23;
    let a = new Animal('lily');
    function People(name) {
        this.name = name
    }
    function fn() {}; // 中转函数
    fn.prototype = Animal.prototype;
    People.prototype = new fn(); // 继承
    let p3 = new People('lisi');
    p3.__proto__.age = 48
    console.log(p3.age) // expect output 48
    console.log(a.age) // expect output 23
    

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- vipyiyao.com 版权所有 湘ICP备2023022495号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务