Javascript 繼承中的一些問題

來源:互聯網
上載者:User

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. }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.