Home > Web Front-end > JS Tutorial > body text

Implement polymorphism in js using methods similar to inheritance_javascript skills

WBOY
Release: 2016-05-16 16:39:09
Original
1099 people have browsed it

Polymorphism can be implemented in a similar way to inheritance. First define an abstract class, which calls some virtual methods. Virtual methods are not defined in the abstract class, but are implemented through its specific implementation class.

As in the following example:

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"
Copy after login

First, an abstract base class base is defined, and the oninit method is called in the initialize method of the base class, but the implementation or declaration of the oninit method is not used in the base class. The SubClassA and SubClassB classes inherit from the base class, and implement the oninit method in different ways.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!