在 Window 对象上设置属性是否被认为是不好的做法? [英] Is setting properties on the Window object considered bad practice?

查看:37
本文介绍了在 Window 对象上设置属性是否被认为是不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个非常复杂的 JavaScript 应用程序,它具有我正在使用 Prototype 的 <实现的 MVC 架构code>Class 支持和模块模式.该应用程序使用 AJAX 和观察者模式.我在 DOM 加载后创建我的控制器实例,向它传递一个视图和一些从 JSON 数据创建的模型,然后它就消失了.

I'm writing a quite complex JavaScript application that has an MVC architecture that I'm implementing using Prototype's Class support and the Module pattern. The application uses AJAX and the Observer pattern. I create my controller instance when the DOM has loaded, pass it a view and some models created from JSON data and away it goes.

但是,我发现我必须将我的控制器实例设置为 Window 对象上的一个属性—即在不使用 var 的情况下声明它—因为我有一个 AJAX 成功回调来刷新控制器拥有的视图对象,而此时在代码中我漂亮的小 MVC 世界不在范围内.

However, I've found that I have to set my controller instance as a property on the Window object—i.e. declare it without using var—because I have an AJAX success callback that refreshes the view object owned by the controller and at this point in the code my nice little MVC world is not in scope.

我调查了将视图对象作为参数传递给包含 AJAX 代码的函数,但这变得非常混乱,并且会导致对 MVC 模式的一些可怕的违反,例如耦合模型和视图.太可怕了.

I investigated passing in the view object as a parameter to the function containing the AJAX code, but this got really messy and would have led to some horrible violations of the MVC pattern, such as coupling the model and the view. It was horrendous.

将我的控制器实例直接存储在 Window 上是否被视为不良形式?这对我来说有点像使用全局变量,但我看不到任何解决方法.

Is doing things like storing my controller instance directly on Window considered bad form? It smells a bit like using a global variable to me, but I can't see any way around it.

推荐答案

在 window 对象上设置属性相当于创建全局变量.也就是说,有时这样做是不可避免的,但您应该尽量将其保持在最低限度,因为它最终会污染全局命名空间.

Setting properties on the window object is equivalent to creating global variables. That is, sometimes doing it is inevitable, but you should try to keep it to a bare minimum, as it ends up polluting the global namespace.

就您而言,创建单个属性还不错.如果您想格外小心,您可以为需要全局访问的任何内容显式创建一个命名空间:

In your case, creating a single property is not so bad. If you want to be extra careful about it, you can explicitly create a namespace for any stuff you need global access to:

// In init:
var mynamespace = {};

. . .

// Once the controller is available:
var namespace = window.mynamespace;
namespace.controller = controller;
namespace.foo = bar; // Set other stuff here as well.

这篇关于在 Window 对象上设置属性是否被认为是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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