Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chapter 4 - Modules : example returns uninitialized variables #65

Open
Pugio opened this issue Mar 13, 2014 · 0 comments
Open

Chapter 4 - Modules : example returns uninitialized variables #65

Pugio opened this issue Mar 13, 2014 · 0 comments

Comments

@Pugio
Copy link

Pugio commented Mar 13, 2014

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant