我理解什么是嵌套函数,但我不明白为什么我们首先需要嵌套函数。 JavaScript 中是否存在只能使用嵌套函数才能解决的问题。我看到的所有创建嵌套函数的示例都可以在无需在函数内部创建函数的情况下进行编码,并且结果相同。那么哪些问题需要创建嵌套函数,并且只能/有效地通过使用嵌套函数来解决。
嵌套函数的核心重要性是作用域生成。我们需要 JavaScript 中的嵌套函数和作用域来实现以下目的。
- 无污染的全局命名空间 https://stackoverflow.com/questions/8862665/what-does-it-mean-global-namespace-would-be-polluted
-
模块化 http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html功能性的
- 封装私有内部运作modules http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
- 防止不同脚本之间的标识符冲突
- 由于嵌套作用域内的变量符合以下条件,因此脚本大小较小缩小化 https://en.wikipedia.org/wiki/Minification_(programming).
- 它加快了标识符解析过程 http://davidshariff.com/blog/javascript-scope-chain-and-closures/
下面是一个示例模块,显示了函数嵌套和作用域提供的封装的强大功能:
var notificationService = (function ($, toastr, undefined) {
var _externals = {},
_jqExtend = $.extend;
/*
* Private Methods
*/
function _showMessage(params) {
params = params || {};
toastr.remove();
if (typeof (params.title) === "undefined")
toastr[params.method](params.msg);
else
toastr[params.method](params.msg, params.title);
}
/*
* Public Members
*/
_externals.clear = function () {
toastr.remove();
};
_externals.showError = function (params) {
params = params || {};
_jqExtend(params, {
method: "error"
});
_showMessage(params);
};
_externals.showInfo = function (params) {
params = params || {};
_jqExtend(params, {
method: "info"
});
_showMessage(params);
};
_externals.showSuccess = function (params) {
params = params || {};
_jqExtend(params, {
method: "success"
});
_showMessage(params);
};
_externals.showWarning = function (params) {
params = params || {};
_jqExtend(params, {
method: "warning"
});
_showMessage(params);
};
return _externals;
})(jQuery, toastr);
上面的代码使我们能够控制要公开的内容。在这种特定情况下,附加到 _externals 对象的所有成员都通过对 notificationService 对象的引用公开到全局命名空间。如果不使用作用域,内部成员(_jqExtend 和 _showMessage)也将附加到窗口对象,并增加浏览器解析标识符引用所需的工作量。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)