面向對象語言有三大特征,前面介紹了封裝和繼承,那么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原生實現的多態就只有函數重寫,其他的形式可以通過某些技巧來模擬。