人生本是一个不断学习的过程,在这个过程中,图老师就是你们的好帮手,下面分享的javascript OOP:实现继承、多态与封装懂设计的网友们快点来了解吧!
【 tulaoshi.com - Web开发 】
代码是随手写的,只提供思路。
这个原理很简单,看代码就懂,不多说了。
(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.will 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. will 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();
来源:http://www.tulaoshi.com/n/20160219/1623963.html
看过《javascript OOP:实现继承、多态与封装》的人还看了以下文章 更多>>