JavaScript中的继承(下)

Posted on 2006-11-28 23:14 Jaunt 阅读(185) 评论(0)  编辑  收藏 所属分类: JavaScript
  作者: Flyingis 
  原载:http://www.blogjava.net/flyingis/archive/2006/07/15/58339.html
    Prototype

   
我们了解到任何prototype的属性和方法都会被传递到该类的所有实例中,利用这一特性,使用prototype也能实现继承。
 
  functionClassA() {
}


ClassA.prototype.id
= 1998;
 ClassA.prototype.sayId
=function(){
   alert(
this.id);
}
;

functionClassB(){
}


ClassB.prototype
=newClassA();
ClassB.prototype.name
="";
 ClassB.prototype.sayName
=function(){
   alert(
this.name);
}

    需要注意的是,这种实现继承的方法不能将参数传入到ClassA的构造器中,是一个缺陷。ClassB的所有属性和方法必需在将ClassB的 prototype对象指向ClassA的实例之后进行附值。这样做是因为,prototype指向一个新的对象,在此之前prototype的属性和方法都被覆盖销毁。

    对代码进行测试:

var obj1 =newClassA();
var obj2=new ClassB();
obj1.id
= 1998;
obj2.id
= 2000;
obj2.name
="悉尼奥运会";
obj1.sayId();  
//输出"1998"
obj2.sayId();  //输出"1998"
obj2.sayName();  //输出"悉尼奥运会"

alert(obj2
instanceofClassA);  //输出"true"
alert(obj2 instanceofClassB);  //输出"true"

    在上述代码中可以看出,使用prototype实现继承,instanceof操作符出现了另外的用途,在用构造起定义类实现继承时,instanceof不会出现这种效果。但是使用prototype不能支持多重继承。
  
    使用构造器定义类实现继承和使用prototype实现继承均存在各自的缺陷,要避免出现这些情况,只有将两者混合使用。

    混合方法

    创建一个类的最佳方法,是使用构造器的方法去定义属性,使用prototype定义方法。在继承中同样如此。

  functionClassA(id) {
  
this.id =id;
}


  ClassA.prototype.sayId
= function() {
   alert(
this.id);
}
;

function ClassB(id, name) {
   ClassA.call(
this, id);
  
this.name =name;
}


ClassB.prototype
=  new ClassA();
 ClassB.prototype.sayName
=function(){
   alert(
this.name);
}

只有注册用户登录后才能发表评论。


网站导航: