zoukankan      html  css  js  c++  java
  • JavaScript继承的实现

    JavaScript继承有构造函数继承、原型继承、复制继承、构造函数/原型组合继承等方法,这些继承方法各有特点。眼下最经常使用的就是构造函数/原型组合继承。

    /**
     * 实现继承
     * @param  subType    {Function}  子类构造函数
     * @param  superType  {Function}  父类构造函数
     */
    function inherit(subType, superType){
        function F(){}
        F.prototype = superType.prototype;
    
        var p = new F();
        p.constructor = subType;
        subType.prototype = p;
    }
    
    /**
     * 父类
     * @param  name  {String}  姓名
     * @param  age   {Number}  年龄
     */
    function Person(name, age){
        this.name = name;
        this.age = age;
    }
    
    Person.prototype.getName = function(){
        return this.name;
    };
    
    Person.prototype.setName = function(name){
        this.name = name;
    };
    
    Person.prototype.getAge = function(){
        return this.age;
    };
    
    Person.prototype.setAge = function(age){
        this.age = age;
    };
    
    
    /**
     * 子类
     * @param  name       {String}  姓名
     * @param  age        {Number}  年龄
     * @param  education  {String}  教育程度
     */
    function Student(name, age, education){
        this.education = education;
    
        //调用父类构造函数
        Person.call(this, name, age);
    }
    
    //实现继承
    //一定要在声明子类原型方法之前,否则会被覆盖。

    inherit(Student, Person); Student.prototype.setEducation = function(education){ this.education = education; }; Student.prototype.getEducation = function(){ return this.education; }; var person = new Person('小明', 25); var student = new Student('小刚', 22, '本科'); person instanceof Person; //true student instanceof Person; //true student instanceof Student; //true

    父类属性及方法

    父类属性及方法

    子类属性及方法
    子类属性及方法!

  • 相关阅读:
    C语言I博客作业09
    请看这里
    C++ 面向对象学习笔记[1]
    graphviz的使用
    KDE安装后的一些随笔
    近期内容整理
    链表
    理解C++ lvalue与rvalue
    再看“笕实智慧校园”——作品的复盘[1]
    无题
  • 原文地址:https://www.cnblogs.com/cxchanpin/p/7151936.html
Copyright © 2011-2022 走看看