我已經看到函數嵌入到結構中,並想知道這是否是一種好的做法。我附上一段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>
JavaScript很靈活。構建代碼有很多不同的方法,而且許多意見都是「良好實踐」,哪些不是。 – 2014-10-06 23:24:37