我见过嵌入在结构中的函数,我想知道这是不是一个好的实践。我附上一段Java脚本来说明这一点。这些数字表示代码流。跟上潮流似乎相当困难。谢谢
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>
发布于 2014-10-07 00:13:48
我见过嵌入到结构中的函数,我想知道这是不是一个很好的实践
是。结构化代码(在这种情况下,将函数放在“命名空间”上)总是一个好主意。
使用(揭示)模块模式通常也是一个好主意,尽管它在这里可能有点过度使用--而不是为每个属性使用一个生命周期,而是为整个anObject
使用一个更大的生命周期。这取决于实际代码中各个部分之间的关系有多密切。
不过,还有一些需要改进的具体问题:
函数anObject.theGuts =(
(){…theGuts })();
这个生命似乎相当无意义,因为它没有设置任何局部变量。此外,由于theGuts
是anObject
对象的一个方法,最好直接在它上面赋值-当需要闭包时,它应该包装整个对象声明。
console.log('In anObject.theGuts');// #1
我不确定这是否会增加代码流的混乱程度,但IIFE最好不要有任何副作用(包括没有日志记录)。
theGuts =函数(N){
你在这里是missing a var
!
this.n = n;
你的方法是在这里创建一个属性?如果这之前是在对象本身“声明”的,那会更好。
函数theGameGuts() {
构造函数的名称应该大写:TheGameGuts
。
this.initGame(); } theGameGuts.prototype.initGame = function() { … }
除非你打算单独调用.initGame()
,否则实例的初始化应该直接在构造函数中完成。不要使用init
方法-它们只会弄乱您的代码流。
https://stackoverflow.com/questions/26226352
复制相似问题