【发布时间】:2014-10-24 16:40:30
【问题描述】:
我的朋友最近开始在他的很多项目中使用 JavaScript,尤其是模块模式。我问他是否可以从他的工作经历中帮助我理解结束: 他把这段代码放在一起来解释模块模式和闭包,但他的代码似乎没有做任何事情..
/* Write JavaScript here */
var test = test || {};
test.application = (function(){
function closure(){
var a = {
name : 'Reena',
age : 32,
doSomeThing: function(){
alert(this.name);
alert(this.age);
}
};
return a;
}
return {
myapp: function(){
var myClosure = closure();
var a = myClosure.doSomeThing();
var myname =myClosure.name;
alert("myname: " + myname);
}
};
})();
当他在 teamview 会话中演示这个时,他开始以一种非常有趣的方式编写模块:他从命名空间对象开始,然后创建一个返回对象的 IIFE Shell 函数,然后开始填充内部函数:
/* Write JavaScript here */
var test = test || {};
test.application = (function(){
function closure(){
//then he worked on this ..
}
return {
//then he worked on the return value for the IIFE which is another javascript function
};
})();
现在,JS 大师能否解释一下为什么他编写的代码没有做任何事情,以及他的示例是否是一个很好的闭包演示。
【问题讨论】:
-
运行测试使用:
test.application.myapp(); -
不应该自动执行吗?
标签: javascript jquery design-patterns closures module-pattern