开发者

why attach to window [edited]

I was looking over the code for qunit.

My question is why would you want 开发者_开发技巧to attach the qunit object via property to window object.

Here is the link to the file. Look at line 11.

If I look at a unit test run using firebug you can see it is a property of window.

[edit] Additional: Is there a specific reference for best practice for declaring things in specific namespaces?


All global objects (functions, variables, etc) are just children of window, it's the default context.

For example: window.jQuery or window.$

It may be easier to think of it this way...where else would you put them? When you're doing something this general, best (or at least easiest) to stick them in the default place. If you're doing something complex with lots of functions, objects, etc...best to put them in a namespace or within an object. For example all of jQuery's code is under jQuery, not littered in the root of the DOM like window.ajax, instead it's jQuery.ajax.

This is much neater, but perhaps overkill when you're dealing with a few items, but it's a good idea to make sure they are unique if this is the case...which qunit does, by prefixing their objects with qunit-


Attaching globals as properties of window is bad practice. All globals should be declared using var. Here's my reasons:

  1. It makes static analysis of source code much harder. It is impossible to tell from looking at a script which globals will be declared and when. Undeclared globals will create ReferenceErrors if they're used. Using var means JavaScript's hoisting takes effect, and mitigates this problem.
  2. Globals made this way are fundamentally different, and there is no easy way for your code to detect this. The biggest difference is the absence of [[DontDelete]] on globals made this way, which means you can delete your global variables. This is silly.
  3. It will tempt you to declare your globals from outside the global scope. This is magic, and bad magic at that. Don't do it.

As far as I'm concerned, the fact that window.x = 1 creates a global variable named x is an interesting curiosity of JavaScript, but should not be used nor replied upon. There are, however, good reasons to use properties of window, since it's an object like any other (more or less). In these cases, you should use the full name, e.g. window.onload instead of just onload.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜