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()
  • 相关阅读:
    转 windows查看端口占用命令
    servlet 让浏览器输出中文,并成功打印出来.2种方法
    ctrl+shift+i eclipse快捷键,debug时显示全黑屏
    转 一台电脑安装多个tomcat
    如何从windows中拷贝文件到linux (ubuntu)??
    Eclipse Java注释模板设置简介,更改字体大小
    sikuli 如何 清空文本框中的内容??解决方法!
    servlet 中通过response下载文件
    servlet乱码 解决方法 2种方法
    关于JAVA路径 问题
  • 原文地址:https://www.cnblogs.com/zlf1914/p/13066270.html
Copyright © 2011-2022 走看看