JavaScript学习总结(十四)——JavaScript编写类的扩展方法

2020-11-28 05:27

阅读:644

标签:des   cWeb   style   blog   class   code   

  在?J?a?v?a?S?c?r?i?p?t?中?可以使?用?类的p?r?o?t?o?t?y?p?e属性来?扩?展?类的属?性?和?方?法,在实际开发当中,当JavaScript内置的那些类所提供的动态方法和动态属性不满足我们实际开发时,我们就可以通过"prototype"属性给自定义类添加方法和属性或者扩展原有的类中的方法和属性。

一、扩展JavaScript内置类,添加动态方法

语法格式:

  类名.prototype.方法名 = function([param1],[param2],....[paramn]) {

    .................

  }

  [param1],[param2],....[paramn]这些参数都是可选的

  使用这种方式给类添加的扩展方法都是动态的,动态方法是针对类的实例对象的,所以调用必须要用"对象.方法名"的形式去调用,不能用"类名.方法名"的形式去调用!

1.1、使用prototype属性扩展String类

  String类是JavaScript内置的一个类,但是这个String类没有quote方法,此时就可以使用String类的prototype属性去扩展String类了,为String类添加一个实例方法(动态方法),这样每一个String类对象就都有quote方法了,这就达到了将String类扩展的效果,增强了String类的使用。

soscw.com,搜素材
1 /*扩展为String类,为String类增加quote(两边加字符)方法*/
2         String.prototype.quote = function(quotestr) {
3             if (!quotestr) {
4                 quotestr = "\"";
5             }
6             return quotestr + this + quotestr;
7         };
soscw.com,搜素材

测试String类新添加的quote方法

soscw.com,搜素材
1 alert("abc".quote());      
2 alert("abc".quote("|"));
soscw.com,搜素材

测试结果:

soscw.com,搜素材soscw.com,搜素材

1.2、使用prototype扩展Number类

soscw.com,搜素材
1 Number.prototype.add=function(n){
2     //哪个对象调用this所在的函数,那么this代表的就是哪个对象实例
3     return this+n;
4 }
soscw.com,搜素材

测试Number类新添加的add方法

soscw.com,搜素材
1 var i= new Number(10);//等价于var i=10;
2 alert("i.Add(10).Add(30)的结果是:"+i.Add(10).Add(30));
3 var b=40;
4 alert("b.Add(90)的结果是:"+b.Add(90));
soscw.com,搜素材

测试结果:

soscw.com,搜素材soscw.com,搜素材

1.3、使用prototype扩展Array类

soscw.com,搜素材
 1 Array.prototype.findVal=function(val){
 2         var index=-1;
 3         //哪个对象调用this所在的函数,那么this代表的就是哪个对象实例
 4         for(var i=0;ithis.length;i++){
 5             if(val==this[i]){
 6                 index=i;
 7                 break;
 8             }
 9         }
10         return index;
11     }
soscw.com,搜素材

测试Array类新添加的findVal方法

soscw.com,搜素材
1 var arr = new Array();
2 arr[0]="孤傲苍狼";
3 arr[1]="白虎神皇";
4 arr[2]="灭世魔尊";
5 alert("arr.FindVal(\"白虎神皇\")返回的索引是:"+arr.FindVal("白虎神皇"));
soscw.com,搜素材

测试结果:

soscw.com,搜素材


评论


亲,登录后才可以留言!