JavaScript protoype继承的简单实现
情境:
有一个父类 Furniture,定义了一个方法 whatAmI,这个方法返回一个简单的 string "furniture"。
定义一个子类 Chair,继承 Furniture 的 whatAmI 方法。
子类继承父类所有的 prototype:
1 // define the super class
2 function Furniture(){}
3 Furniture.prototype.whatAmI = function()
4 {
5 return "furniture";
6 }
7
8 // define extendBy method in which all its prototypes are extended by
9 // a given class name
10 Furniture.extendBy = function( className )
11 {
12 for(var i in this.prototype){
13 if( eval(className).prototype[i] != undefined )
14 continue;
15 eval(className).prototype[i] = this.prototype[i];
16 }
17 }
18
19 // define the sub class Chair, and extend all the
20 // prototypes Furniture has
21 function Chair()
22 {
23 Furniture.extendBy(arguments.callee.name);
24
25 // more code ...
26 }
一个子类可以从多个不同的父类中继承方法,根据 Furniture.extendBy 方法里的实现 (第 13 行),同名的方法以顺序最初继承的那个为准,当然这是可以更改的。
extendBy 方法还可以做更多的更改,实现选择性继承。
选择一部分方法进行继承:
1 Furniture.extendBy = function( className )优质内容筛选与推荐>>
2 {
3 if( this.EXT_LIST == undefined ){
4 this.EXT_LIST = [ "whatAmI" ];
5 }
6 for(var i=0; i<this.EXT_LIST.length; i++){
7 if( eval(className).prototype[this.EXT_LIST[i]] != undefined )
8 continue;
9 eval(className).prototype[this.EXT_LIST[i]] = this.prototype[this.EXT_LIST[i]];
10 }
11 }