zoukankan      html  css  js  c++  java
  • JS 中的继承

    原生JS(ES5)中的继承

    对象冒充继承: 没法继承原型链上面的属性和方法
    function Person(name, age) {
        this.name = name;
        this.age = age;
        this.run = function () {
            console.log(`${this.name} is ${this.age}岁`)
        }
    }
    Person.prototype.sex = '男'
    Person.prototype.work = function () {
        console.log(`${this.name} is ${this.sex} and ${this.age}岁`)
    }
    
    function Man(name, age) {
        Person.call(this, name, age) //对象冒充实现继承
    }
    
    var man = new Man('sally', 18)
    man.run()
    man.work()
    
    /**
      man.work is not a function
    */
    

      

    原型链继承:可以继承构造函数里面以及原型链上面的属性和方法,实例化子类的时候没法给父类传参

    function Person(name, age) {
        this.name = name;
        this.age = age;
        this.run = function () {
            console.log(`${this.name} is ${this.age}岁`)
        }
    }
    Person.prototype.sex = '男'
    Person.prototype.work = function () {
        console.log(`${this.name} is ${this.sex} and ${this.age}岁`)
    }
    
    
    //原型链继承
    function Man(name, age) {}
      
    Man.prototype = new Person() 
    
    var man = new Man('sally', 18)
    man.run()
    man.work()
    
    /**
      undefined is undefined岁
      undefined is 男 and undefined岁
    */
    

      

    采用原型链继承和对象冒充继承相结合的方式继承:

    function Person(name, age) {
        this.name = name;
        this.age = age;
        this.run = function () {
            console.log(`${this.name} is ${this.age}岁`)
        }
    }
    Person.prototype.sex = '男'
    Person.prototype.work = function () {
        console.log(`${this.name} is ${this.sex} and ${this.age}岁`)
    }
    
    //对象冒充实现继承
    function Man(name, age) {
        Person.call(this, name, age) 
    }
    //原型链继承
    Man.prototype = new Person() 
    
    var man = new Man('sally', 18)
    man.run()
    man.work()
    
    
    /**
     * sally is 18岁
     * sally is 男 and 18岁
     */
    

      

    ES6 中的继承

    通过 extends 关键字:

    class Person {
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
        getInfo() {
            console.log(`姓名:${this.name} 年龄:${this.age}`);
        }
        run() {
            console.log('run')
        }
    }
    class Man extends Person {  //继承了Person  extends  super(name,age);
        constructor(name, age, sex) {
            super(name, age);   //实例化子类的时候把子类的数据传给父类
            this.sex = sex;
        }
        print() {
            console.log(this.sex);
        }
    }
    var man = new Man('jack', '30', '男');
    man.getInfo();
    
    /**
     * 姓名:jack 年龄:30
     */
    

      

  • 相关阅读:
    Java异常之初认识二
    Java异常之初认识
    enum类型用于switch语句
    数组指定元素查找 之 二分法查找
    数组元素查找 之 线性查找
    数组的反转
    枚举类 Enum 之初认识
    求数组元素的最大值,最小值,总和,平均数
    clone()方法引发的对protected权限修饰符的思考
    完成一个朋友圈的表设计
  • 原文地址:https://www.cnblogs.com/shanlu0000/p/13172520.html
Copyright © 2011-2022 走看看