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

Javascript
动态改变图片尺寸(一)
JavaScript+PHP 应用一:网页制作中双下拉菜单的动态实现
JavaScript + PHP 应用二:网页设计中树形菜单的动态实现
在Javascript中为String对象添加trim,ltrim,rtrim方法
纯JavaScript时钟
网页之定时器详解
为网页添加活动的背景音乐
Javascript Game
实用的检测分辨率的程序代码
【推荐】一个非常漂亮的列表框
绝对精彩:在网页里做类似window右键的弹出式菜单
怎样使网页中的元素可编辑??
JavaScript和Java的区别
怎样编写IE和NN6通用的闪烁(blank)效果
关于如何动态地在同一页面实现两个 < select > 互传 (s1 <==> s2)
COOKIE欺骗
连串英文自动换行的方法
JavaScript中的正则表达式(1)
JavaScript中的正则表达式(2)
JavaScript窗口功能指南之定制新窗口

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


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