首页 > 语言 > JavaScript > 正文

Javascript继承机制详解

2024-05-06 15:16:35
字体:
来源:转载
供稿:网友

学完了Javascript类和对象的创建之后,现在总结一下Javascript继承机制的实现。Javascript并不像Java那样对继承机制有严格明确的定义,它的实现方式正如它的变量的使用方式那样也是十分宽松的,你可以设计自己的方法“模仿”继承机制的实现。有以下几种方法:

1、对象冒充

 <script type="text/javascript">   function classA(str){     this.str=str;     this.printstr=function(){       document.write(this.str);       document.write("<br>");     }     this.getstr=function(){       return this.str;     }       }   function classB(name,str){     //下面这两句代码相当于将classA代码体中的内容搬到这里     this.newMethod1=classA;     this.newMethod1(str);     //注意,这里的写法     delete this.newMethod1;     //新的方法和属性的定义须在删除了newMethod之后定义,因为可能覆盖超类的属性和方法。     this.name=name;     this.sayName=function(){       document.write(this.name);       document.write("<br>");     }        }   var a=new classB("Amy","helloworld");   a.printstr();   alert(a.getstr());   a.sayName(); </script>

function定义的代码块就相当于一个类,你可以用而且它有this关键字,你可以用this为它添加属性和方法,上述代码中有以下两句:

this.newMethod1=classA;
 this.newMethod1(str);

classB中定义了newMethod1变量,它是一个引用,指向了classA,并且还调用了classA,这两句代码的作用等同于直接将classA代码块中的内容直接复制到这里,这样创建的classB对像当然具有classA的属性和方法了。对象冒充还可以实现多继承,如下:

function ClassZ() { this.newMethod = ClassX; this.newMethod(); delete this.newMethod;this.newMethod = ClassY; this.newMethod(); delete this.newMethod;}

不过,classY会覆盖classX中同名的属性和方法,如果设计没问题的话,classz也不应该继承具有相同属性和方法的不同类。

2、利用call()方法

 <script type="text/javascript">   function classA(str){     this.str=str;     this.printstr=function(){       document.write(this.str);       document.write("<br>");     }     this.getstr=function(){       return this.str;     }       }   function classB(name,str){   //利用call方法实现继承     classA.call(this,str);     this.name=name;     this.sayName=function(){       document.write(this.name);       document.write("<br>");     }        }   var a=new classB("Amy","helloworld");   a.printstr();   alert(a.getstr());   a.sayName(); </script>

call()方法中第一个参数传递一个对象,这里的this指的是当前对象,后面的参数(可能有多个)是指传递给调用call()方法的类(函数)所需要的参数,classA.call()也是相当于直接将classA代码块中的内容直接复制到这里,classB的对象同样可以直接使用classB中的变量和方法。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选