我刚刚阅读了关于Java脚本中模块模式的代码项目的一篇小文章。在阅读javascript代码后,几乎没有很明确的代码写入方式。我写了JavaScript,但我不熟悉事先写入JavaScript的方式。这里是我从CodeProject http://www.codeproject.com/Articles/619747/Module-Pattern-in-Java-Script-in-Depth关于JavaScript中的模块模式
1)读取URL //对于添加数字
生成一个新的函数的函数function addGenerator(num) {
// Return a simple function for adding two numbers
// with the first number borrowed from the generator
return function (toAdd) {
return num + toAdd
};
}
// addFive now contains a function that takes one argument,
// adds five to it, and returns the resulting number
var addFive = addGenerator(5);
// We can see here that the result of the addFive function is 9,
// when passed an argument of 4
alert(addFive(4) == 9); // Which return true
时addGenerator呼吁然后5已通过作为参数,但我只是做
不懂这条线是怎么回事
return function (toAdd) {
return num + toAdd
};
addGenerator(5)会返回什么?
这将如何返回true - > alert(addFive(4)== 9); //哪个返回true
2)
var EmployeeModule = (function (my) {
my.anotherFunction = function() {
return alert('this is another function.');
};
} (EmployeeModule));
上面的代码将如何工作&将被调用?请详细说明他们正在尝试做什么?
3)
var EmployeeModule = (function (my) {
// add functionality...
return my;
}(EmployeeModule || {}));
我只是不明白这行(EmployeeModule || {}))
请解释此行的意义。
4)全球进口的模块模式
我们也可以导入其他Java脚本库在我们的模块
(function ($, Y) {
// now have access to globals jQuery (as $) and YAHOO (as Y) in this code
}(jQuery, YAHOO));
Sub-modules in Module Pattern
有很多情况下,我们可以创建子模块。这就像创建一个常规模块 Collapse |复制代码
EmployeeModule.subModule = (function() {
var my = {};
// ...
return my;
}());
寻找上述代码点明智的更好的解释与更多的例子更好的解释。谢谢
我认为您理解所有代码所需了解的概念并非特定顺序:类型转换,短路运算符,立即调用的函数表达式(IIFE),闭包,高阶函数和部分应用程序。 – elclanrs