2011-02-06 30 views
1

是否有可能創建一個構造函數並讓它運行其中的代碼,類似於C#和Java等語言?下面的代碼是我所瞭解的。如何設置和運行JavaScript的構造函數

例如

function Test() 
{ 
     Test.constructor = function() 
     { 
      /* Run code inside here when created */ 
     } 
} 


    var test = new Test(); 
+0

我想通了。我正在尋找類中的自調用函數來在創建實例時執行代碼 – chobo 2011-02-06 02:01:59

回答

4

功能測試可以構造本身,如果你使用new運算符調用它。

function Test() { 
    /* Run code inside here when created */ 
} 

... 

var test = new Test(); 

您可以通過分配方法:

Test.prototype.aMethod = function() { 
    /* Run code inside here when invoked */ 
} 

test.aMethod(); 
3

是的,它是更簡單

function Test() 
{ 
    /* Run code inside here when created */ 
} 

var test = new Test();