O
ociardhp
Hi
I've seen some code similar to the following and would like to confirm
my understanding. I assume the object literal created in the return
has access to the enclosing scope which includes the variable age,
effectively creating a closure over it when created, and that this is
what enables the assignment to moon.age? Is this considered good style
and is there any particular reason for using that approach as opposed
to the clearer (in my opinion) declaration of age within the object
literal?
Many thanks
Paul
<html>
<body>
<div id="holder"></div>
<script>
moon = function() {
var age;
return {
// age: 4000000000,
showDarkSide: function() {
return false;
}
}
}();
moon.age = 42;
document.getElementById("holder").innerHTML = "Age: " + moon.age +
"<br/> ShowDarkSide: " + moon.showDarkSide();
</script>
</body>
</html>
I've seen some code similar to the following and would like to confirm
my understanding. I assume the object literal created in the return
has access to the enclosing scope which includes the variable age,
effectively creating a closure over it when created, and that this is
what enables the assignment to moon.age? Is this considered good style
and is there any particular reason for using that approach as opposed
to the clearer (in my opinion) declaration of age within the object
literal?
Many thanks
Paul
<html>
<body>
<div id="holder"></div>
<script>
moon = function() {
var age;
return {
// age: 4000000000,
showDarkSide: function() {
return false;
}
}
}();
moon.age = 42;
document.getElementById("holder").innerHTML = "Age: " + moon.age +
"<br/> ShowDarkSide: " + moon.showDarkSide();
</script>
</body>
</html>