JS多态

面向对象语言有三大特征,前面介绍了封装和继承,那么JS作为一门面向对象语言,有多态么,又怎么实现多态呢?

我们先看看多态的概念:

多态:同一操作作用于不同的对象,可以有不同的解释,产生不同的执行结果。

PS(多态其实是强类型结的果,而对于JS这种本身就是【弱类型】的语言来说,多态是与生俱来的,或者说根本就不需要这个概念。比如同一个“+”在字符串之间、数值之间执行不同的运算,就是一种多态。)

那么严格意义的多态怎么实现呢

多态最常见的三中方式

  • 重写
  • 重载
  • 接口

     重写指子类重新定义父类方法,这正好就是基于prototype继承的玩法

function aaron(){}
aaron.prototype.say=function(){
      alert("hi");
}
function aaron1(){
  this.say=function(){
      alert("hello");
}
}
aaron1.prototype=new aaron();
var ni=new aaron1();
ni.say();

        重载是指多个同名但参数不同的方法,这个JavaScript确实没有,但是我们可以绕个大弯来实现,根据arguments来判断参数个数和类型,然后再函数体中分情况执行不同的代码。

bar1 = function ( a ) { console.log( a ) };

bar2 = function ( a, b ) { console.log( a + b ) } 

foo = function () {
        if ( arguments.length === 1 ) {
               bar1.apply(null, arguments)
           }
       if ( arguments.length === 2 ) {
              bar2.apply(null, arguments)
          }
}

  接口我们也可以曲线来实现,把接口需要实现的方法都抛出异常,如果没有被实现就会报错。

//interface
function Parent() {
       this.print = function(){throw 'No implementation';};
}

function ChildA() {
       this.print = function(){alert('ChildA');};
}
ChildA.prototype = new Parent();

function ChildB() {
       this.print = function(){alert('ChildB');};
}
ChildB.prototype = new Parent();

function ChildC() {}
ChildC.prototype = new Parent();

var p = new ChildA();
p.print();

p = new ChildB();
p.print();

p = new ChildC();
p.print();

  结语:js原生实现的多态就只有函数重写,其他的形式可以通过某些技巧来模拟。

原文地址:https://www.cnblogs.com/aaronchu/p/6169843.html