zoukankan      html  css  js  c++  java
  • 构造函数继承与class继承

    构造函数继承

    1、子类通过apply方法或者call方法把this指向父类

    js代码

            function Parent(name, age) {
                this.name = name
                this.age = age
            }
            Parent.prototype.init = function(){
                console.log(this.name, this.age) 
            }
            function Son(name, age) {
                Parent.apply(this, [name, age]) //子类通过apply方法或者call方法把this指向父类
            }

    这种方法继承了父类的属性,然而并没有继承父类原型上方法

    2、把父类实例对象赋值给子类原型

    js代码

            function Parent(name, age) {
                this.name = name
                this.age = age
            }
            Parent.prototype.init = function(){
                console.log(this.name, this.age) 
            }
            function Son(name, age) {
                
            }
            Son.prototype = new Parent() //把父类实例对象赋值给子类原型
            Son.prototype.constructor = Son //严谨起见,不写也不会影响效果

    这虽然继承了父类原型方法,但是却没有继承父类属性

    把1、2这两者综合一下就是构造函数的组合继承了,这样就实现了继承父类的方法和属性

    js代码

            function Parent(name, age) {
                this.name = name
                this.age = age
            }
            Parent.prototype.init = function(){
                console.log(this.name, this.age) 
            }
            function Son(name, age) {
                Parent.call(this,name,age) //子类通过apply方法或者call方法把this指向父类
            }
            Son.prototype = new Parent() //把父类实例对象赋值给子类原型
            Son.prototype.constructor = Son //严谨起见,不写也不会影响效果

    组合继承:缺点,实现继承的过程中调用了两次父类实例

    class继承

    1、通过extends关键字继承父类原型方法,super方法继承父类属性,

    js代码

            class Parent{
                constructor(name,age) {
                    this.name = name
                    this.age = age
                }
                init(){
                    console.log(this.name,this.age)
                }
            }
            class Son extends Parent{ //extends关键字继承父类原型方法
                constructor(name,age) {
                   super(name,age) //super方法继承父类属性
                }
            }
            new Son('张三',18).init()
  • 相关阅读:
    接口和抽象的区别
    继承-子父类中成员方法特点
    基本类型和引用类型作为参数传递
    大三寒假生活6
    大三寒假生活5
    大三寒假生活4
    大三寒假生活3
    大三寒假生活2
    大三寒假生活指导
    ajax实现文本框的联想功能
  • 原文地址:https://www.cnblogs.com/zlf1914/p/13066270.html
Copyright © 2011-2022 走看看