js 几种继承的方式

原型链继承:

        优点: 父类方法可以复用

        缺点: 父类的所有引用类型(数组对象),会被子类共享,改一个子类数据,其他数据都会收到影响

     function Person() {
            this.name = '张三';
            this.eats = ['香蕉', '苹果'];
            this.getName = function () {
                console.log(this.name);
            }

        }

        Person.prototype.get = function () {
            console.log('Person 继承的方法');
        }

        function Student() {

        }

        Student.prototype = new Person
        console.log('------------------p1---------------');

        const p1 = new Student()
        p1.get()
        p1.eats.push('橘子') // p1 更改了 eats 数组里面的值 ,p2 拿到的就是更改之后的值
        p1.name = '李四'    // 更改 name 值 ,p2 不受影响
        console.log(p1.name);
        console.log(p1.eats);

        console.log('-----------------p2----------------');
        const p2 = new Student()
        console.log(p2.name);
        console.log(p2.eats);
        p2.get()

 构造函数继承

        优点:父类的应用类型不会被子类所更改,不会互相影响

        缺点: 子类不能访问父类原型属性的方法和参数

        function Person() {
            this.name = '张三';
            this.eats = ['香蕉', '苹果'];
            this.getName = function () {
                console.log(this.name);
            }

        }

        Person.prototype.get = () => {  // 此方法不能使用
            console.log('Person 继承的方法');
        }

        function Student() {
            Person.call(this) // 指向 Student
        }

        console.log('-----------------p1----------------');
        const p1 = new Student()
        p1.name = 'ssss'
        p1.eats.push('菠萝') // 只会自己更改,不会影响别人
        console.log(p1);

        console.log('-----------------p2----------------');
        const p2 = new Student()
        console.log(p2);

 

 

 此时我们来 输出 get 方法,是不存在的

组合继承

        优点:1.父类可以复用

                   2.父类构造函数的引用属性不会被共享

        缺点:会调用两次父类的构造函数,会有两份一样的属性和方法,会影响性能

 function Person() {
            this.name = '张三';
            this.eats = ['香蕉', '苹果'];
            this.getName = function () {
                console.log(this.name);
            }

        }

        Person.prototype.get = () => {
            console.log('Person 继承的方法');
        }

        function Student() {
            Person.call(this)
        }

        Student.prototype = new Person  // 增

        const p1 = new Student()
        console.log(p1);

 

 寄生组合继承

      function Person() {
            this.name = '张三';
            this.eats = ['香蕉', '苹果'];
            this.getName = function () {
                console.log(this.name);
            }

        }

        Person.prototype.get = () => {
            console.log('Person 继承的方法');
        }

        function Student() {
            Person.call(this)
        }
        // 创建一个中转站
        const Fn = function () { }
        Fn.prototype = Person.prototype

        Student.prototype = new Fn()  // 增

        const p1 = new Student
        p1.get()
        console.log(p1);

 

猜你喜欢

转载自blog.csdn.net/Cat_LIKE_Mouse/article/details/125865505