0

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/

4

1 に答える 1

3

「あなたのアプローチの何が問題になっているのか」は、これがモジュールパターンではないということです。それを使用するつもりなら、それを使用して、その関数を自己呼び出しにする:

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

関数ではなく、その無名関数がすでに呼び出されているため、後で関数として呼び出すことはありません。mySceneそして、見てください、あなたはまだそのサークルにアクセスできます!

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

括弧(無名関数を呼び出す)を省略すると、ご存知のように、結果が大きく異なります。

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

于 2013-01-29T03:06:43.710 に答える