2017-09-14 58 views
-1

我很清楚,沒有直接的方法來定義JavaScript中的類。根據此article,JavaScript中沒有class關鍵字。但我們可以使用function關鍵字來激發類似行爲。如何在JavaScript類中定義構造函數?

現在我的問題是,有沒有什麼方法可以像C/C++那樣定義一個構造函數,只要創建這個不那麼類的實例,它就會自動執行?

+0

你谷歌JavaScript構造?這應該是很容易找到的信息。 – Carcigenicate

+2

您的信息已過時。截至今天,Javascript [完全支持](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)類和構造函數。 – georg

回答

1

,你可以調用你的類constructor(args){}並使用它。

E.g:

class Dummy { 
    constructor(Param){ 
     // what you want 
    } 

} 
+0

我不確定這是否回答了問題,因爲OP似乎是指ES6之前的版本。但是,這是未來的答案。 – Carcigenicate

1

除InternetExplorer的,在他們的當前版本的現代瀏覽器實際上支持的是class關鍵字和意義。

Read here

甚至在此之前的constructor存在,不得不在其他任何OO語言相同的作用。

僞類定義

function MyClass(){ 
    // this is the constructor if you don't plan to define one in prototype 
    // as I do below 
    // code that will be executed on every instance of MyClass  
}; 

隱含定義構造函數

MyClass.prototype.constructor = function(){ 
    // code that will be executed on every instance of MyClass 
}; 

,然後

var myInstance = new MyClass(); // constructor will be auto called. 
相關問題