为什么我将窗口对象传递给模块模式? [英] Why do I pass the window object in to the module pattern?

查看:53
本文介绍了为什么我将窗口对象传递给模块模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个自动执行的匿名方法。

Here is a self executing anonymous method.

将窗口作为全局传递似乎是一种好习惯。如果窗口随处可用,为什么要这样做?

It seems to be good practice to pass in window as global. If window is available everywhere already why is this done?

(function (global) { 

 /* my code */ 

 global["someName"] = someObject; 

})(window);


推荐答案

它跳过了必须进行范围查找的代码全局的范围是函数内部。

It skips the code having to do a scope lookup since global is scoped inside the function.

编辑 - 这是性能优化。 javascript中的范围仅限于函数范围。在这种情况下, global 正在该范围内定义,因此当代码点击 global [...] 时,它看起来在它的直接范围内(在函数内)并立即找到 global 。如果没有它,那么它将不得不移动到闭包范围,在这种情况下是全局javascript命名空间,并搜索整个范围窗口

Edit -- It's a performance optimization. Scoping in javascript is limited to function scope. global in this case is being defined within that scope, so when the code hits global[...] it looks at it's immediate scope (within the function) and finds global right away. Without that it would then have to move up to the closure scope, which in this case is the global javascript namespace, and search that entire scope for window.

这篇关于为什么我将窗口对象传递给模块模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆