js继承的几种方式

20 阅读1分钟

这是自己学习js继承方式的时候验证知识点写的一些测试代码,用于自学

    // 原型链式继承,会共享内存空间
        function Parent() {
            this.name = 1
            this.color = [1,2]
        }
        function Child() {
            this.age = 1
        }
        Child.prototype = new Parent()
        let p1 = new Child()
        let p2 = new Child()
        p1.color.push(4)
        console.log(p1);
        console.log(p2);

        // 构造函数继承,变量不会共享内存空间,但是无法继承方法
        function Car() {
            this.speed = 1
            this.color = [1,2,3]
        }
        function Bigcar() {
            Car.call(this)
            this.weight = 1
        }
        let car1 = new Bigcar()
        let car2 = new Bigcar()
        car1.color.push(11)
        console.log(car1);
        console.log(car2);

        // 组合式继承,综合原型链式继承和构造函数继承的优点,但是会调用两次父构造函数
        function Aniaml() {
            this.name = 1
        }
        Aniaml.prototype.changeName = function() {
            this.name++
        }
        function Cat() {
            //第二次调用
            Aniaml.call(this)
            this.age = [1,2,3]
        }
        Cat.prototype = new Aniaml()
        Cat.prototype.constructor = Aniaml
        let cat1 = new Cat()
        let cat2 = new Cat()
        cat1.changeName()
        console.log(cat1);
        console.log(cat2);
        
        //使用Object.create()的原型继承以及寄生式继承,由于该方法是浅拷贝,多个实例的引用类型指向相同的内存

        function Student() {
            this.name = 1
        }
        Student.prototype.changeName = function() {
            this.name++
        }
        function Bigstudent() {
            Student.call(this)
            this.Studentcode = 2
        }
        function clone(parent,child) {
            child.prototype = Object.create(Student.prototype)
        }
        clone(Student,Bigstudent)
        let stu1 = new Bigstudent()
        let stu2 = new Bigstudent()
        stu1.changeName()
        console.log(stu1);
        console.log(stu2);