当前位置: 首页 > 图文教程 > 网络编程 > Javascript > javascript 面向对象编程基础 多态

Javascript
xp风格菜单
具有edit功能的combobox
可以编辑的Select (第二版)
IE6.0打印机制解析
JScript5.5下String.prototype.replace(str,func)的UBB嵌套的递归解开。
vbscript和javascript互相调用方法
转换大写中文数字
Freeonline在线编辑器(自由软件)
对象化JS之----文件上传客户端控制脚本
对象化JS之----日期选择
对象化JS之----仿outlook或者QQ的菜单
如何使用Shell.Application技术
模拟windows control的进度条
双向链表&&堆栈
网页中的媒体播放器
如何在页面显示来访者分辨率,浏览器(js)
子父窗口之间的操作之小例子
JavaScript 实现日历式日期选择
页面上的javascript判断
在客户端用JAVASCRIPT或VBSCRIPT生成WORD文档

Javascript 中的 javascript 面向对象编程基础 多态


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 128 ::
收藏到网摘: n/a

javascript 面向对象编程基础 多态 的实现方法说明,大家可以看下下面的代码。 js的重载和重写(覆写):
重载的意思是,“同一个名字的函数(注意这里包括函数)或方法可以有多个实现,它们依靠参数的类型和(或)参数的个数来区分识别”。而重写(覆盖)的意思是,“子类中可以定义与父类中同名,并且参数类型和个数也相同的方法,这些方法的定义后,在子类的实例化对象中,父类中继承的这些同名方法将被隐藏”。重载的英文是overload,覆盖的英文是override。好了,概念介绍到这里,你猜到我要说什么了吗?嘿嘿,Code is cheap.看重载代码:
// 通过函数的arguments属性实现重载
function add() {
var sum = 0 ;
for ( var i = 0 ; i < arguments.length; i ++ ) {
sum += arguments[i];
}
return sum;
}
function test() {
alert(add());
alert(add( 1 , 2 ));
alert(add( 1 , 2 , 3 ));
}
通过代码运行结果,这样就实现了任意多个参数加法函数的重载了。当然,你还可以在函数中通过 instanceof 或者 constructor 来判断每个参数的类型,来决定后面执行什么操作,实现更为复杂的函数或方法重载。总之,javascript 的重载,是在函数中由用户自己通过操作 arguments 这个属性来实现的。关于arguments的特性,前面我已经做了简单介绍,参考拙文:http://blog.csdn.net/zhanglingdll_39/archive/2009/08/20/4465670.aspx 。
下面重点理解js重写的实现:
// 为类添加静态方法inherit表示继承于某类
Function.prototype.inherit = function (baseClass) {
for ( var p in baseClass.prototype) {
this .prototype[p] = baseClass.prototype[p];
}
}
// js实现重写
function parentClass() { // 父类
}
parentClass.prototype.method = function () {
alert( " parentClass method " );
}
function subClass() { // 子类
}
// 下面这一句和subClass.prototype = new parentClass();等价
subClass.inherit(parentClass);
// subClass.prototype.method = function() { // 子类重写了父类的方法 -- 去掉注释运行试试看
// alert("subClass method");
// }
function test() {
var obj = new subClass();
obj.method();
}
这样,子类中定义的method 就覆盖了从父类中继承来的method 方法了。这是你可能会问,如何在子类中调用父类的method方法呢?好的,看实现如下:
// 为类添加静态方法inherit表示继承于某类
Function.prototype.inherit = function (baseClass) {
for ( var p in baseClass.prototype) {
this .prototype[p] = baseClass.prototype[p];
}
}
/* 参考文章:http://menjoy.javaeye.com/blog/127847 */
// js实现重写
function parentClass() {
this .method = function () {
alert( " parentClass method " );
}
}
function subClass() {
var method = this .method;
this .method = function () {
method.call( this );
alert( " subClass method " );
}
}
subClass.prototype = new parentClass();
// subClass.inherit(parentClass); //这一句貌似和上一句subClass.prototype = new parentClass();等价,其实呢????(注释上一行,运行这一行看看)
subClass.prototype.constructor = subClass;
function test() {
var obj = new subClass();
obj.method();
}
好了,关于多态的介绍就到这里。js面向对象编程犹如浩瀚海洋广阔无边,我这三篇参考别人的文章写出来的js面向对象基础只能当作入门者学习的参考。学无止境,参考了网上几篇老大们的牛文,深知自身技术的浅薄,对于已经超越了解阶段的读者,还是看看园子里高人的技术文章吧。我这里要先拜谢园子里的高人了。