gpt4 book ai didi

Javascript 揭示模块模式 Noob

转载 作者:行者123 更新时间:2023-11-28 20:40:04 24 4
gpt4 key购买 nike

我正在启动 Addy Osmani 的 amazing book on javascript design patterns但似乎无法起步。谁能告诉我我的方法有什么问题(我使用 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/

最佳答案

“你的方法有什么问题”是 this isn't the module pattern 、揭示或其他方式。如果您打算使用它,请使用它,并让该函数自调用:

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/

关于Javascript 揭示模块模式 Noob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14574960/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com