2014-10-06 19 views
0

我已經看到函數嵌入到結構中,並想知道這是否是一種好的做法。我附上一段Java腳本來說明這一點。數字是指代碼流。遵循流程似乎相當不容易。 感謝將js函數放置在一個對象中

anObject = {}; // an empty object 
 
anObject.theGuts = (function() { 
 
    console.log('In anObject.theGuts'); // #1 
 
    theGuts = function(n) { 
 
    this.n = n; 
 
    console.log('theGuts called with:'); 
 
    console.log(this.n); // #6 
 
    } 
 
    return theGuts; 
 
})(); 
 

 
anObject.theGame = (function() { 
 
    function theGameGuts() { 
 
    console.log('In theGameGuts'); // #4 
 
    this.initGame(); 
 
    } 
 
    var p = theGameGuts.prototype; 
 
    p.initGame = function() { 
 
    console.log('in initGame'); // #5 
 
    anObject.theGuts(2); 
 
    } 
 
    return theGameGuts; 
 
})() 
 

 
console.log('the anObject'); 
 
console.log(anObject); // #2 
 

 
window.onload = function() { 
 
    console.log('In window.onload'); //#3 
 
    // entry point 
 
    var game = new anObject.theGame(); 
 
    console.log('the game: '); 
 
    console.log(game); // #7 
 
};
<head> 
 
    <meta charset="utf-8"> 
 
    <title>An edmbed test</title> 
 

 
    <script type="text/javascript"> 
 
    function init() { 
 

 
    } 
 
    </script> 
 

 
</head> 
 

 
<body>Some text 
 
    <script type="text/javascript" src='javaScript.js'></script> 
 
</body>

+1

JavaScript很靈活。構建代碼有很多不同的方法,而且許多意見都是「良好實踐」,哪些不是。 – 2014-10-06 23:24:37

回答

0

我見過嵌入的結構功能和想知道,如果這是很好的做法

是。構造代碼(在這種情況下,將函數放在「命名空間」上)總是一個好主意。

使用(透露)模塊模式通常也是一個不錯的主意,但它可能是這裏有點過度使用 - 而不是使用每個屬性的一個IIFE,一個可能已經使用一個單一的,對於較大的一個整個anObject。取決於實際代碼中各部分之間的相互關係有多緊密。


一些改進的具體問題,但:

anObject.theGuts = (function() { 
    … theGuts 
})(); 

這IIFE似乎是毫無意義的,因爲它不設置任何局部變量。另外,因爲theGuts是對象的一種方法,所以最好直接賦值它 - 當需要閉包時,它應該包裝整個對象聲明。

console.log('In anObject.theGuts'); // #1 

不知道這是否增加了很多你的代碼流的混亂,但IIFEs最好不要有任何副作用(包括沒有日誌記錄)。

theGuts = function(n) { 

missing a var這裏!

this.n = n; 

你的方法創建的屬性嗎?如果這是之前被「聲明」在對象本身的話,會更好。

function theGameGuts() { 

構造函數的名稱應該大寫:TheGameGuts

this.initGame(); 
    } 
    theGameGuts.prototype.initGame = function() { 
    … 
    } 

除非你打算單獨調用.initGame(),實例的初始化直接在構造函數本身來完成。不要使用init方法 - 它們只會弄亂你的代碼流。

相關問題