• JavaScript面向对象之继承和多态


    前言:我之前已经写过了javascript如何创建一个类似于java写法的类User,并且也写了一些类似的一些写法。

    既然关注了面向对象的类,就无可避免地要提到面向对象的特性:封装,继承和多态。

    封装:封装就像是一个类,它把对象类似于表格数据单元存储起来,对外只提供属性和方法。

    继承:继承就是在类的基础之上加以扩展使现有的类属性更加全面,做的事情甚至更多(当然也可以完全不做任何修改,直接拿来使用)。

    多态:动态的调用类型或接口方法,自动完成类型匹配。下面代码为证:

    1、封装一个User类,作为基类

    /**
      *声明一个类似于java的类并添加其属性
      */
     var User=function(){
       var name='jack';//默认值
       var gender=‘male’;//默认值
       var age=20;//默认值
       this.setName=function(name){
            this.name=name;
      };

       this.getName=function(){

           return this.name;

     }
       this.setGender=function(gender){
           this.gender=gender;
      };

      this.getGender=function(){

        return this.gender;

     }
     this.setAge=function(age){
           this.age=age;
      };

     this.getAge=function(){

         return this.age;

      }

     this.introduceMyself=function(){

         alert('Hello!my name is '+this.getName()+",I'm "+this.getAge()+'years old!');

    }
    }

    2、继承:创建User的子类

    派生出子类Bluce并重写介绍自己的方法。

    var Bluce=function(){

       this.introduceMyself=function(){

         alert('Bluce say hello to you!');

        }

    }

    派生出子类Lisa并重写自己的介绍方法。

    var Lisa=function(){

    this.introduceMyself=function(){  

         alert('Lisa  say hello to you!');

       }

    }

    /**

     *多态方法

     */

    function sayHello(intro){

        // 判断实参是否是User的一个实例

        if (intro instanceof User) {

        // 调用sayHello方法(编译器会自动获取被覆盖过的子类方法并调用)

         intro.introduceMyself();

       }

    }

    实现继承:

    Bluce.prototype=new User();

    Lisa.prototype=new User();

     3、多态调用

    var  ub=new Bluce();

    ub.setName("Bluce");

    ub.setAge(23);

    ub.setGender('male');

    ub.sayHello(ub);

     

    var ul=new  Lisa();

    ul.setName("Lisa");

    ul.setAge(21);

    ul.setGender('female');

    ul.sayHello(ul);

  • 相关阅读:
    网络流24题
    Preliminaries for Benelux Algorithm Programming Contest 2019
    2019 ICPC Asia Xuzhou Regional
    2019 ICPC Asia Nanjing Regional
    后缀自动机学习
    2018 ACM-ICPC 焦作区域赛 E Resistors in Parallel
    2019 ICPC 上海区域赛总结
    LA 3641 Leonardo的笔记本 & UVA 11077 排列统计
    UVA 10294 项链与手镯 (置换)
    CF 1288 E. Messenger Simulator
  • 原文地址:https://www.cnblogs.com/boonya/p/2498102.html
Copyright © 2020-2023  润新知