JavaScript原型继承

138 阅读1分钟

组合继承

     <body>
        <!-- 也叫伪经典继承
            将原型链继承和构造函数继承组合在一块
            原型链实现对原型属性和方法的继承
            借用构造函数实现对实例属性的继承
        -->
        <script>
            function Person(){
                /* 实例属性 */
                this.head=1
                this.foot=2
            }

            /* 原型的属性和方法 */
            Person.prototype.weight='70kg'
            Person.prototype.eat=function(){
                document.write('我会吃饭');
            }

            function Student(){
                /* 借用构造函数实现对实例属性的继承 */
                Person.call(this)
            }

            /* 原型链实现对原型属性和方法的继承 */
            Student.prototype=new Person()
            Student.prototype.contructor=Student
            let st1=new Student()
            console.log(st1);
            st1.eat()
        </script>
    </body>
    
    

拷贝继承

     <script>
            /* 父类 */
            function Person() { }
            /* 子类 */
            function Student() { }
            Person.prototype.head = 1
            Person.prototype.foot = 2
            Person.prototype.eat = function () {
                document.write('123');
            }
            jc(Student,Person)
            /* for (let key in Person.prototype) {
                Student.prototype[key] = Person.prototype[key]
            } */
            /* new产生了实例stu1,把构造函数Student()的属性方法都给了实例
            构造函数Bc的this是指向实例stu1 */
            let stu1 = new Student();
            console.log(stu1);
            stu1.eat()
            /* 封装 */
            function jc(child,parent) {
                for (let key in parent.prototype) {
                    child.prototype[key] = parent.prototype[key]
                }
            }
     </script>