当前位置导航:炫浪网>>网络学院>>网页制作>>JavaScript教程

javascript OOP:实现继承、多态与封装

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

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


 


(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();

相关内容
赞助商链接