javascript-allonge
javascript-allonge copied to clipboard
Chapter 4 - Modules : example returns uninitialized variables
In the following snippet, the returned module contains three properties that all resolve to 'undefined'. While the variables (drawLine, drawRect, drawCircle) are all in scope at the beginning of the function, they would only be initialized after control hits the the return statement.
var DrawModule = (function () {
return {
drawLine: drawLine,
drawRect: drawRect,
drawCircle: drawCircle
}
// public methods
var drawLine = function (screen, leftPoint, rightPoint) { ... }
var drawRect = function (screen, topLeft, bottomRight) { ... }
var drawCircle = function (screen, center, radius) { ... }
To fix this, just change the var statements into named function declarations:
return {
drawLine: drawLine,
drawRect: drawRect,
drawCircle: drawCircle
}
// public methods
function drawLine (screen, leftPoint, rightPoint) { ... }
function drawRect (screen, topLeft, bottomRight) { ... }
function drawCircle (screen, center, radius) { ... }
Each of these functions exist for the entire scope of the closure, and will return correctly from the initial return statement.