2019-08-27

Javascript的多态性

1.js不支持重载

/*****************说明js不支持重载*****/

function Person(){

    this.test1=function (a,b){

        window.alert('function (a,b)'); 

    }

    this.test1=function (a){

        window.alert('function (a)');

    }

}

var p1=new Person();

//js中不支持重载.

//但是这不会报错,js会默认是最后同名一个函数,可以看做是后面的把前面的覆盖了。

p1.test1("a","b");

p1.test1("a");

2.js如何实现重载

//js怎么实现重载.通过判断参数的个数来实现重载

function Person(){

    this.test1=function (){

        if(arguments.length==1){

            this.show1(arguments[0]);

        }else if(arguments.length==2){

            this.show2(arguments[0],arguments[1]);

        }else if(arguments.length==3){

            this.show3(arguments[0],arguments[1],arguments[2]);

        }

    }

    this.show1=function(a){

        window.alert("show1()被调用"+a);

    }

    this.show2=function(a,b){

        window.alert("show2()被调用"+"--"+a+"--"+b);

    }

    function show3(a,b,c){

        window.alert("show3()被调用");

    }

}

var p1=new Person();

//js中不支持重载.

p1.test1("a","b");

p1.test1("a");

多态的基本概念

// Master类

function Master(name){

    this.nam=name;

    //方法[给动物喂食物]

}

//原型法添加成员函数

Master.prototype.feed=function (animal,food){

    window.alert("给"+animal.name+" 喂"+ food.name);

}

function Food(name){

    this.name=name;

}

//鱼类

function Fish(name){

    this.food=Food;

    this.food(name);

}

//骨头

function Bone(name){

    this.food=Food;

    this.food(name);

}

function Peach(name){

    this.food=Food;

    this.food(name);

}

//动物类

function Animal(name){

    this.name=name;

}

//猫猫

function Cat(name){

    this.animal=Animal;

    this.animal(name);

}

//狗狗

function Dog(name){

    this.animal=Animal;

    this.animal(name);

}

//猴子

function Monkey(name){

    this.animal=Animal;

    this.animal(name);

}

var cat=new Cat("猫");

var fish=new Fish("鱼");

var dog=new Dog("狗");

var bone=new Bone("骨头");

var monkey=new Monkey("猴");

var peach=new Peach("桃");

//创建一个主人

var master=new Master("zs");

master.feed(dog,bone);

master.feed(cat,fish);

master.feed(monkey,peach);

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,167评论 0 10
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 13,170评论 0 13
  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 6,169评论 0 2
  • 1. 组合继承:又叫伪经典继承,是指将原型链和借用构造函数技术组合在一块的一种继承方式。 下面来看一个例子: fu...
    HJHA阅读 1,814评论 0 0
  • 找到fullcalendar.js, 找到代码为 isRTL:false,这句话 输入以下几句 monthName...
    迷你小小白阅读 5,649评论 0 1

友情链接更多精彩内容