简单的多态也许大家会经常用到.
如
function add(x,y){
return x+y;
}
add(10,30);
add("a","b");
然而,下面是比较经典的js实现多态的方法,下面我把代码贴下
<script type="text/javascript">
function dwn(s){
document.write(s+"<br/>");
}
function Animal(){
this.bite=function(){
dwn("animal bite!");
}
}
function Cat(){
this.bite=function(){
dwn("Cat bite!");
}
}
Cat.prototype=new Animal(); ///inherit Animal
function Dog(){
this.bite=function(){
dwn("Dog bite");
}
}
Dog.prototype=new Animal(); ///inherit Animal
function AnimalBite(animal){
if(animal instanceof Animal) ///instanceof bite Dog.bite() and Cat.bite()
animal.bite();
}
var cat=new Cat();
var dog=new Dog();
AnimalBite(cat);
AnimalBite(dog);
</script>