JavaScript/jQuery 中各种函数作用域/事件绑定的优缺点 [英] Pros and Cons of Various Function Scopes/Event Binds in JavaScript/jQuery
问题描述
以下函数作用域的优缺点是什么:
全局函数/内联 JS
<块引用><button id="buttA" onclick="funcA();">点击我</button>
全局函数/非内联 JS
<块引用><button id="buttA">点击我</button>
非全局函数/非内联 JS
<块引用><button id="buttA">点击我</button>
哪种组合更好,为什么?
我认为不使用全局变量的重要论据来自网络协作的性质.如果您正在构建一个站点范围的脚本,并且您有一个团队(假设有两个人在开发插件),那么您不希望您的变量被您的合作者覆盖或调用.此外,让人们不断要求您向他们提供程序变量和函数的列表会减慢一切.
/* 私有命名空间 */(功能 () {var sum_1 = 10;var sum_2 = 20;var myFunction = 函数 (x, y) {返回 x * y;};myFunction(sum_1, sum_2);})();
What are the pros and cons of the following function scopes:
Global Function/Inline JS
<script> function funcA() { //do something } </script> <button id="buttA" onclick="funcA();">Click Me</button>
Global Function/Non-inline JS
<script> function funcA() { //do something } $(function() { $('#buttA').on('click', funcA); }); </script> <button id="buttA">Click Me</button>
Non-global Function/Non-inline JS
<script> $(function() { $('#buttA').on('click', funcA); function funcA() { //do something } }); </script> <button id="buttA">Click Me</button>
Which combination is better and why?
I think the big argument to not use global variables comes with the nature of web collaboration. If you're build a site-wide script, and you have a team of lets say two others working on plugins, you don't want your variables to be overwritten or invoked by your collaborators. Additionally, having people consistently asking you to provide them with a list of your program variables and functions is going to slow everything down.
/* Private namespace */
(function () {
var sum_1 = 10;
var sum_2 = 20;
var myFunction = function (x, y) {
return x * y;
};
myFunction(sum_1, sum_2);
})();
这篇关于JavaScript/jQuery 中各种函数作用域/事件绑定的优缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!