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

Javascript
提高网站信任度的技巧
javascript脚本编程解决考试分数统计问题
图片上传之前检查大小、尺寸、格式并预览的js代码
JavaScript打开客户端exe文件的代码
JavaScript confirm选择判断
javascript title闪动效果
javascript把15位身份证转成18的函数
新人报道,发个小技巧(js数组重复判断)
Javascript this关键字使用分析
javascript TextArea动态显示剩余字符
JavaScript Undefined,Null类型和NaN值区别
javascript Select标记中options操作方法集合
javascript trim 去空格函数实现代码
javascript网页关闭时提醒效果脚本
checkbox 多选框 联动实现代码
收集的比较全的automation服务器不能创建对象 异常原因和解决方法
Javascript客户端将指定区域导出到Word、Excel的代码
IE浏览器兼容Firefox的JS脚本的代码
在html页面中包含共享页面的方法
javascript replace()用法详解附实例代码

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 264 ::
收藏到网摘: 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面向对象基础只能当作入门者学习的参考。学无止境,参考了网上几篇老大们的牛文,深知自身技术的浅薄,对于已经超越了解阶段的读者,还是看看园子里高人的技术文章吧。我这里要先拜谢园子里的高人了。