JavaScript如何实现高级语言的继承

一、对象冒充

code:

<script type="text/javascript">
 function Parent(username)
 {
  this.username = username;
  this.getInfo = function()
  {
   alert(this.username);
  }
 }
 
 function Child(username,password)
 {
  this.method = Parent;
  this.method(username);
  delete this.method;//这三行代码是本质s
  this.password = password;
  this.getInfo = function()
  {
   alert(this.username + ":" + this.password);
  }
 }
 
 var c = new Child("crossci","qq:1306338080");
 c.getInfo();
</script>

-----------------------------------------------------

二、使用call方式

code:

<script type="text/javascript">
 function Parent(username)
 {
  this.username = username;
  this.getInfo = function()
  {
   alert(this.username);
  }
 }
 
 function Child(username,password)
 {
  Parent.call(this,username);//这行代码是本质
  this.password = password;
  this.getInfo = function()
  {
   alert(this.username + ":" + this.password);
  }
 }
 
 var c = new Child("crossci","qq:1306338080");
 c.getInfo();
</script>

-----------------------------------------------------

三、使用apply方式

code:

<script type="text/javascript">
 function Parent(username)
 {
  this.username = username;
  this.getInfo = function()
  {
   alert(this.username);
  }
 }
 
 function Child(username,password)
 {
  Parent.apply(this,[username]);
  this.password = password;
  this.getInfo = function()
  {
   alert(this.username + ":" + this.password);
  }
 }
 
 var c = new Child("crossci","qq:1306338080");
 c.getInfo();
</script>

-----------------------------------------------------

四、使用原型链方式

code:

<script type="text/javascript">
 function Parent(username)
 {
  this.username = username;
  this.getInfo = function()
  {
   alert(this.username);
  }
 }
 
 function Child(username,password)
 {
  this.password = password;
  this.getInfo = function()
  {
   alert(this.username + ":" + this.password);
  }
 }
 Child.prototype = new Parent();//让Child的prototype对象指向一个Parent对象,那么Child就具有了这个对象的所有属性
 
 var c = new Child("crossci","qq:1306338080");
 c.getInfo();
</script>

-----------------------------------------------------

五、混合方式

code:

<script type="text/javascript">
 function Parent(username)
 {
  this.username = username;
 }
 Parent.prototype.getInfo = function()
 {
  alert(this.username);
 }
 function Child(username,password)
 {
  this.password = password;
  this.getInfo = function()
  {
   alert(this.username + ":" + this.password);
  }
 }
 Child.prototype = new Parent();
 
 var c = new Child("crossci","qq:1306338080");
 c.getInfo();
</script>

-----------------------------------------------------

注:1.通过Child.prototype = new Parent();这种方式的继承会使父类属性被子类的对象共享,如果属性是原型数据类型那么父类属性类似子对象的私有属性,而对象型数据类型的会被共享(方法可以,但对象的私有属性就不合逻辑了)

posted @ 2012-02-11 22:39  Crossci  阅读(148)  评论(0编辑  收藏  举报