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 }
优质内容筛选与推荐>>
1、Git常用功能记录
2、实例化讲解 RunLoop
3、JQuery事件对象的属性和方法
4、Linq 动态组合排序(Lambda)
5、C# GC 垃圾回收机制


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn