我的 friend 最近开始在他的很多项目中使用 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 session 中演示这一点时,他开始以一种非常有趣的方式编写模块:他从命名空间对象开始,然后创建一个返回对象的 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 = ( ... )();
执行匿名 JavaScript 函数,该函数返回一个对象:
{
myapp: function(){ ... }
}
因此要运行它,您必须:
test.application.myapp();
关于一些关闭:
myapp(){
this => { myapp: function(){ ...} }
myapp => function(){ ... }
closure => function(){ ... }
name => undefined
age => undefined
doSomething => undefined
}
closure().myapp => undefined
closure().closure => undefined
closure().name => "Reena"
closure().age => 32
closure().doSomething => function(){ ... }
doSomeThing(){
myapp => undefined
closure => function(){ ... }
name => undefined
age => undefined
doSomeThing => undefined
this => { name: 'Reeva', age: 32, doSomeThing: function() { ... }
}
关于javascript - 模块模式和闭包讨论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26552418/