简体   繁体   English

不确定此js代码在执行Calendar脚本

[英]Not sure what this js code is doing Calendar script

This bit of code just makes my brain hurt, js is not my strong point 这段代码只是让我的大脑受伤,js不是我的强项

I have tried adapting it, and managed to make the browser crash (endless loop i am guessing) 我试图适应它,并设法使浏览器崩溃(我猜是无限循环)

to me it looks like if window.load != function then create new calendar, otherwise do whatever window.load wants to do, followed by create new calendar 在我看来,如果window.load!=函数然后创建新的日历,否则执行window.load想做的任何事情,然后创建新的日历

is that correct? 那是对的吗?

Why would it need to be wrapped in (function() {} ? 为什么需要将其包装在(function(){}中?

(function() {
   var my = function() { new Calendar($option_str).show(); };
   var other = window.onload;
   window.onload = typeof other != 'function' ? my : function() { other(); my(); };
})();

The (function(){})() is an immediately invoked function expression (IIFE). (function(){})()是立即调用的函数表达式(IIFE)。 The reason for doing that is to protect the global scope from being polluted by those variable names, and also to make it easier to be garbage collected going forward. 这样做的原因是为了保护全局范围不受那些变量名的污染,并且使以后更容易进行垃圾收集。

The reason this is possible is because the function expression creates a new execution context for the code executing. 之所以可行,是因为函数表达式为代码执行创建了新的执行上下文。 This execution context creates its own variable environment which is where the variable my and the variable other reside. 该执行上下文创建自己的变量环境,变量my和变量other驻留在该环境中。 The context also has access to the lexical environment which is where window resides. 上下文还可以访问窗口所在的词法环境。

As for saving the onload callback, checking if it is a function, and then calling what was there along with the new code that is to ensure that the onload function is not overwritten. 至于保存onload回调,请检查它是否是一个函数,然后调用其中的内容以及新代码以确保onload函数不会被覆盖。 This can be unfortunate when loading many libraries in the head of the document, and making sure not to step on other people's onload is important. 当在文档的开头加载许多库时,这可能是不幸的,并且确保不踩别人的负担很重要。

So basically the reason boils down to a few main aspects 所以基本上原因归结为几个主要方面

  • It makes garbage collection easier 它使垃圾收集更加容易
  • It avoids polluting the global namespace 它避免污染全局名称空间
  • It preserves previous onload events 它保留以前的onload事件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM