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

Javascript
js操作ajax返回的json的注意问题!
javascript document.compatMode兼容性
jquery 锁定弹出层实现代码
Jquery+CSS 创建流动导航菜单 Fluid Navigation
js下用层来实现select的title提示属性
JSON 学习之JSON in JavaScript详细使用说明
jquery实现的超出屏幕时把固定层变为定位层的代码
jQuery 性能优化手册 推荐
javascript Firefox与IE 替换节点的方法
ext combox 下拉框不出现自动提示,自动选中的解决方法
json-lib出现There is a cycle in the hierarchy解决办法
判断控件是否已加载完成的代码
javascript for循环设法提高性能
js 表格拖拽效果实例代码 (IE only)
javascript 命名规则 变量命名规则
js 面向对象的技术创建高级 Web 应用程序
User agent字符串将成为用户真正的隐私问题
JS教程:JavaScript全半角转换
JS教程:Chrome对数组的sort方法优化
WEBJX收集非常有用的免费的Javascript开发工具

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


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