Home  >  Article  >  Web Front-end  >  js中实现多态采用和继承类似的方法_javascript技巧

js中实现多态采用和继承类似的方法_javascript技巧

WBOY
WBOYOriginal
2016-05-16 16:39:091031browse

多态的实现可以采用和继承类似的方法。首先定义一个抽象类,其中调用一些虚方法,虚方法在抽象类中没用定义,而是通过其具体的实现类来实现。

如下面的例子:

Object.extend=function(destination,source){ 
for(property in source){ 
destination[property]=source[property]; 
} 
return destination; 
} 
//定义一个抽象基类base,无构造函数 
function base(){}; 

base.prototype={ 
initialize:function(){ 
this.oninit();//调用了一个虚方法 
} 
} 
function SubClassA(){ 
//构造函数 
} 
SubClassA.prototype=Object.extend({ 
propInSubClassA:"propInSubClassA", 
oninit:function(){ 
alert(this.propInSubClassA); 
} 
},base.prototype); 

function SubClassB(){ 
//构造函数 
} 
SubClassB.prototype=Object.extend({ 
propInSubClassB:"propInSubClassB", 
oninit:function(){ 
alert(this.propInSubClassB); 
} 
},base.prototype); 

var objA=new SubClassA(); 
objA.initialize();//输出"propInSubClassA" 

var objB=new SubClassB(); 
objB.initialize();//输出"propInSubClassB"

首先定义了一个抽象基类base,在base类的initialize方法中调用了oninit方法,但是基类中并没用oninit方法的实现或者声明。SubClassA和SubClassB类继承自base类,并且分别采用了不同的方式对oninit方法进行实现。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn