Question

I'm starting Addy Osmani's amazing book on javascript design patterns but can't seem to get off the ground. Can anyone tell me what's wrong here with my approach (I'm using Raphael, just for fun.):

var myPaper = Raphael('container', '800', '600');

var myScene = function() {
  var c1 = myPaper.circle(50, 50, 40);
  var c2 = myPaper.circle(50, 150, 40);
  var c3 = myPaper.circle(50, 250, 40);

  c2.attr("fill", "red");  // yep!

  return {
      firstCircle: c1
  };
}

// at some point later i want to call the function...
myScene();

//  ...then even later I want to refer to one of the circles
//  but without creating another global variable.

myScene.firstCircle.attr("fill", "red");  // nope!
console.log(myScene.firstCircle); //  undefined!

http://jsfiddle.net/aGCv8/

Was it helpful?

Solution

"What's wrong with your approach" is that this isn't the module pattern, revealing or otherwise. If you meant to use it, use it, and make that function self-invoking:

var myScene = function() {
  var c1 = myPaper.circle(50, 50, 40);
  var c2 = myPaper.circle(50, 150, 40);
  var c3 = myPaper.circle(50, 250, 40);

  c2.attr("fill", "red");  // yep!

  return {
      firstCircle: c1         // ← refer to a variable which is actually defined
  };
}();                          // ← parens go here

You don't later call myScene as a function, because it isn't a function, and that anonymous function has already been called. And look, you still get access to that circle!

console.log(myScene.firstCircle); // z {0: circle.[object SVGAnimatedString], node: circle.[object SVGAnimatedString], id: 0, matrix: cb, realPath: null, paper: j…}

Omitting the parentheses (which call the anonymous function) leads to a very different outcome, as you have found.

http://jsfiddle.net/mattball/qR4Fj/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top