继承 (ES5)

作者: 七_五 | 来源:发表于2017-11-28 00:17 被阅读0次

    1、定义

    继承是一个对象可以直接使用另一个对象的属性和方法

    目的:
    1、得到一个类的属性
    2、得到一个类的方法

    首先我们定义两个类

    //定义Person类
    function Person(name, sex) {
      this.name = name
      this.sex = sex
    }
    
    Person.prototype.printName = function() {
      console.log(this.name)
    }
    
    //定义Male类
    function Male(age) {
       this.age = age
    }
    Male.prototype.printAge = function() {
       console.log(this.age)
    }
    

    2、 属性的继承

    更改Male,写法如下:

    function Male(name, sex, age){
        //当我们new一个新的Male对象的时,会执行Person构造函数
        //通过this将环境改到自己的作用域内,从而将属性赋值到自己的内部
        Person.call(this, name, sex);
        this.age = age;
    }
    

    3、方法的继承

    我们通过Object.create()这个方法来实现Person原型方法继承到Male上,对于这个方法不了解的可以先参考mdn上的文档

    //Object.create()继承Person方法
    //相当于Male.prototype.__proto__ = Person.prototype
    Male.prototype = Object.create(Person.prototype)
    

    demo演示

    最后大家想看一个完整版的继承实现,可以参考我在github上的源码:
    https://github.com/joinmouse/ES6/tree/master/class_extends,欢迎star

    相关文章

      网友评论

        本文标题:继承 (ES5)

        本文链接:https://www.haomeiwen.com/subject/raejbxtx.html