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

Javascript
实现表格中行点击时的渐扩效果!
多图展示滑动过渡效果
弹出自适应图片大小的窗口弹出窗口根据图片大小,自动判断高和宽。
拖动Html元素集合 Drag and Drop any item
脚本吧 - 幻宇工作室用到js,超强推荐base.js
使用透明叠加法美化文件上传界面
JavaScript高级程序设计
对象的类型:本地对象(1)
如何实现表格中行点击时的渐扩效果!
使用button标签,实现三态图片按钮
根据分辩率调用不同的CSS.
Web版彷 Visual Studio 2003 颜色选择器
JS中简单的实现像C#中using功能(有源码下载)
js之WEB开发调试利器:Firebug 下载
jQuery中文入门指南,翻译加实例,jQuery的起点教程
jQuery 1.0.4 - New Wave Javascript(js源文件)
强悍无比的WEB开发好助手FireBug(Firefox Plugin)
换肤测试程序js脚本
xWin之JS版(2-26更新)
共享自己写一个框架DreamScript

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


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