假设我有这段代码 ( fiddle ) 旨在内存模块:
var chat = {
// Create this closure to contain the cached modules
module: function() {
// Internal module cache.
var modules = {};
console.log('in module:', name); // <---------- "in return: result"
// Create a new module reference scaffold or load an
// existing module.
return function(name) {
console.log('in return:', name); // <---------- "in return: derp"
// If this module has already been created, return it.
if (modules[name]) {
return modules[name];
}
// Create a module and save it under this name
return modules[name] = { Views: {} };
};
}()
};
chat.module("derp");
代码中根本没有提到“结果”这个短语。为什么它会在第一个控制台日志中返回该值?
此外,当 module: function() {}
声明中未指定任何参数时,返回函数如何获取 name
参数的值?
最佳答案
console.log('in module:', name);
您在声明name
之前就记录了它。所以它使用 window.name
相反。
关于javascript - 为什么我得到的闭包值为 "result"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12165693/