JS類中定義原型方法的兩種實現的區別_javascript技巧

來源:互聯網
上載者:User
我們知道,給JavaScript類添加原形(prototype)方法是很簡單的。而且常用的有下面這兩種方法,可是這兩種方法在使用時有區別嗎?

    JScript Class:
 function JSClass()
 {

 }
    Extends prototype method:
 JSClass.prototype.MethodA = function()
 {

 };
    Or

 function = JSClass.prototype.MethodA()
 {

 };
其實這兩個原形定義方式可以簡化一下來討論,先把它們看作是兩個函數,如下: 
  Foo1(); 

  function Foo1() 
  { 
      alert(’This is Foo1.’); 
  }
     和   Foo2(); 
  var Foo2 = function() 
  { 
      alert(’This is Foo2.’); 
  }

     運行第一個顯然是不會有任何錯誤的,可是運行第二個就有問題了,這時系統會說:Microsoft JScript runtime error: Object expected。這就是說函數定義(Foo1)在指令碼解析器中有最高的初始化優先順序,這個很好理解。如果不優先處理函數,那麼對於函數中的函數調用就沒有辦法處理了,假使我們先定fn1()再定義fn2(),卻從fn1中調fn2,那麼就通不過解析了。為什麼Foo2不能被初始化,Foo2的定義根本不是函數定義,它是一個標準的指派陳述式,之所以能象標準函數一樣的使用Foo2(Foo2()),完全是因為它指向的是一個函數對象的執行個體而已。
再來看原形方法匯入裡的兩種方式,就很簡單了。並且不同的執行優先循序,也決了它們在使用中的不同,看如下樣本: 
<script language="javascript">
function NormalClass() 
{ 
    this.m_Property1 = ’P1 in Normal Class.’; 
    this.m_Property2 = ’P2 in Normal Class.’; 

    this.toString = function() 
    { 
         return ’[class NormalClass]’; 
    }

    return new InnerClass();   

    function InnerClass() 
    { 
         this.m_Property1 = ’P1 in Inner Class.’;  
         this.m_Property2 = ’P2 in Inner Class.’;  

         this.toString = function() 
         { 
              return ’[class InnerClass]’; 
         }     
    }

    InnerClass.prototype.Method1 = function() 
    { 
         alert(this.m_Property1); 
    }; 

    function InnerClass.prototype.Method2() 
    { 
         alert(this.m_Property2); 
    };   
}
</script>

     執行: 
var nc = new NormalClass(); 
nc.Method1(); 
nc.Method2();

     是什麼效果?為什嗎? 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.