Chinaunix首页 | 论坛 | 博客
  • 博客访问: 55509
  • 博文数量: 3
  • 博客积分: 800
  • 博客等级: 准尉
  • 技术积分: 160
  • 用 户 组: 普通用户
  • 注册时间: 2004-11-06 22:51
文章分类

全部博文(3)

文章存档

2008年(3)

我的朋友

分类: 系统运维

2008-09-13 13:07:32

代码是随手写的,只提供思路。

这个原理很简单,看代码就懂,不多说了。


 


(function (){
var h = 0;
handle = function (){return h++};
var f = function (){};
extend = function (a, b){
    f.prototype = a;
    var ret = new f;
    if (typeof b == 'function') {
        b.call(ret);
    } else if (typeof b == 'object') {
        for (var key in b) {
            ret[key] = b[key];
        }
    }
    return ret;
};
})();

(function (){
ClassA = function (){
    this.hello = 'world';
};
ClassA.virtualmethod = handle();
ClassA.prototype = extend({}, function (){
    this.virtualmethod = function (){
        var impl = this[ClassA.virtualmethod];
        if (impl) {
            impl.apply(this, arguments);
        } else {
            alert('ClassA.virtualmethod not yet impl.');
        }
    };
});
})();

(function (){ // ClassB extend ClassA

ClassB = function (){
    ClassA.apply(this, arguments);
};

// 继承性

ClassB.prototype = extend(ClassA.prototype, function (){
    this[ClassA.virtualmethod] = function (){
        alert('this is ClassA.virtualmethod, impl in ClassB.\nwill show this.hello.');
        alert('this.hello = ' + this.hello);
    }
    
    // 封装性

    this.test = this.virtualmethod;
    this.virtualmethod = undefined;
});
})();

(function (){ // ClassC extend ClassB

ClassC = function (){
    ClassB.apply(this, arguments);
};

ClassC.prototype = extend(ClassB.prototype, function (){
    // 多态性

    var impl = this[ClassA.virtualmethod];
    this[ClassA.virtualmethod] = function (){
        alert('this is ClassA.virtualmethod, impl in ClassC. \nwill run ClassB\'s impl.');
        impl.apply(this, arguments);
    };
});
})();

// test case

var a = new ClassA;
a.virtualmethod(); // not yet impl


var b = new ClassB;
b.test();
alert('b.virtualmethod is: '+b.virtualmethod);

var c = new ClassC;
c.test();

阅读(434) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~