简体   繁体   English

Javascript揭示模块模式Noob

[英]Javascript revealing module pattern Noob

I'm starting Addy Osmani's amazing book on javascript design patterns but can't seem to get off the ground. 我正在开始关于JavaScript设计模式的 Addy Osmani 令人惊叹的书,但似乎起步并不顺利。 Can anyone tell me what's wrong here with my approach (I'm using Raphael, just for fun.): 谁能告诉我我的方法有什么问题(我使用Raphael只是为了好玩。):

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/ http://jsfiddle.net/aGCv8/

"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. 以后不要myScene称为函数,因为它不是函数,并且该匿名函数已经被调用。 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/ http://jsfiddle.net/mattball/qR4Fj/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM