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

王朝html/css/js·作者佚名  2008-09-02
窄屏简体版  字體: |||超大  

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

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

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

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航