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);