2015-03-03 164 views
0

所以我對JavaScript(來自強大的java背景)不熟悉,我想知道在類或構造函數中定義屬性或變量的正確方法。在Javascript構造函數中定義屬性的正確方法

function RootNode(sTitle, authName, storyNum){ 
    this.sTitle = sTitle; 
    this.authName = authName; 
    this.storyNum = storyNum; 
    this.creationDate = new Date(); 
} 

function RootNode(sTitle, authName, storyNum){ 

    var sTitle = sTitle; 
    var authName = authName; 
    var storyNum = storyNum; 
    var creationDate = new Date(); 
} 
+0

#1。在#2中創建局部變量。 – 2015-03-03 02:53:44

+0

JavaScript中沒有類(至少尚未)。 – 2015-03-03 02:54:28

+0

當有,我不會使用它們。 https://www.youtube.com/watch?v=PSGEjv3Tqo0 – m59 2015-03-03 02:55:10

回答

3

答案很簡單:使用第一個


更詳細的解答

的第一個片段設置sTitleauthNamestoryNumcreationDate屬性。

第二個片段創建4個局部變量並設置它們的值。這些變量在函數外部是不可訪問的。

可以使用局部變量和對象變量一起這樣的:

function RootNode(sTitle, authName, storyNum) { 
    this.sTitle = sTitle; // you can access this variable when you . into the object 

    var privateVariable = 'You cannot see this variable when you . into the object directly'; 
    this.methodInObject = function() { 
     return privateVariable; // but you can access the variable from the function 
    } 
} 

注:你可能想在構造函數的末尾添加return this;,使其返回對象你構建的。

UPDATE:%的評論,你做必須return this;爲使用new RootNode這是否自動將


進一步閱讀(+1使用自動的:)?)

+1

返回'this'是不必要的,因爲'new'已經爲你做了。 – plalx 2015-03-03 03:18:58

+0

@plalx感謝您指出。我不知道(或者如果我知道了,我會忘記)。我已經開悟了。 – 2015-03-03 03:28:00

+0

構造函數必須返回一個對象。如果沒有這樣做的返回語句,它將返回由* this *引用的對象。有些人喜歡爲清晰起見而使用'return this',儘管沒有參數(例如沒有返回值,如果在調用中省略* new *,函數將返回* undefined * - 儘早破解)。 – RobG 2015-03-03 03:36:49

0

可以使用的第一個樣式,但我個人比較喜歡這樣的:http://www.w3schools.com/js/js_objects.asp

+0

我認爲OP正試圖以「僞古典」的方式使用JS。 – 2015-03-03 02:55:25

+0

w3schools ...那些可怕的人... – Travis 2015-03-03 02:58:20

+0

@jsve「僞古典」莊園會是什麼?來自java和c的強大背景是否有一種不同的方法,我應該給予javascript的觀點? – crazyCoder 2015-03-03 02:58:39

0

第一種方式是正確的。

function RootNode(sTitle, authName, storyNum) { 
    this.sTitle = sTitle; 
    this.authName = authName; 
    this.storyNum = storyNum; 
    this.creationDate = new Date(); 
} 

然而,這種方法不是很喜歡的一類,它更多的是獨特的對象。以這種方式定義對象更像是一個Java類。

function RootNode(sTitle, authName, storyNum) { 
    //your constructor 
    this.sTitle = sTitle; 
    this.authName = authName; 
    this.storyNum = storyNum; 
    this.creationDate = new Date(); 
} 

RootNode.prototype.myMethod = function() { 
    //my code 
} 

這種模式很有用,因爲它允許多個實例化,而不需要爲屬性複製內存。另外,如果你想創建子類,這是必要的。閱讀this瞭解原型和構造函數屬性

+0

爲什麼'var RootNode = function'比直接函數聲明更好?這實際上更糟,因爲構造函數是未命名的。用你提出的構造,'RootNode.name'將返回空字符串。 – plalx 2015-03-03 03:20:58

+0

這是一個很好的觀點。我的重點是原型。我會編輯它。 – 2015-03-03 03:23:16

相關問題