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"
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.