现在的位置: 首页 > 综合 > 正文

Javascript 继承中的一些问题

2012年02月05日 ⁄ 综合 ⁄ 共 911字 ⁄ 字号 评论关闭

Javascript 的继承类问题,已经被说烂了,  其核心只有一点在 子类B()中 运行 父类A().

一个简洁的实现:

  1. function B( arg1, arg2)//假设子类B有两个初始值,其中arg1是传递给父类A
  2. {
  3.    //继承A
  4.    A.call( this, arg1 );//这里假设父类A有一个初始值
  5. }

最近发现在函数继承有些问题,

请看下面:

假设A:

  1. function A( arg1 )
  2. {
  3.     this.m1= arg1;
  4.     this.oCap = document.getElementById(arg1);
  5.        this.oCap.onmousedown = this.CaptureMouse(this);
  6. }
  7. //外部定义A的成员函数
  8.  A.prototype.CaptureMouse = function( oThis )
  9.  {
  10.         return function()
  11.         {
  12.            oThis.oCap.setCapture(true);
  13.         }
  14. }

此时, A() 自身,运行良好.

但是,问题出现在当B()继承A时, 解释器无法解释CaptureMouse

可能在B()中运行A时, 解释器对A的解释是采用顺序解释方法,所以处在后面的A.prototype.CaptureMouse没有被发现,所以会有这种现象.

在改成如下代码后,

问题解决:

  1. function A( arg1)
  2. {
  3.     this.m1= arg1;
  4.     this.oCap = document.getElementById(arg1);
  5.     //先定义函数CaptureMouse
  6.     this.CaptureMouse = function( oThis )
  7.     {
  8.         return function()
  9.         {
  10.            oThis.oCap.setCapture(true);
  11.         }
  12.     }
  13.     //再应用CaptureMouse
  14.     this.oCap.onmousedown = this.CaptureMouse(this);
  15. }

 

抱歉!评论已关闭.