6

I don't know if you need to see the full code, but I have seen a few plugins that do this:

window.dataValidate = dataValidate

Does this add 'dataValidate' to the window object, or how does it work?

1
  • It copies dataValidate to a global variable with the same name. Commented May 25, 2013 at 10:04

1 Answer 1

7

Does this add 'dataValidate' to the window object

Yes, it will.

For example, if you're inside another scope;

function foo() {
    var bar = 4;

    window.bar = bar;
}

You've now made bar global, and can access it from anywhere. Without the window.bar = bar, you'd only have been able to access it within foo().

You'll commonly see this being used at the end of an IIFE, to publish work to the rest of the world (e.g. jQuery);

(function () {
   var jQuery;

   // Setup jQuery

   window.jQuery = jQuery;
}());

You might see people doing this instead;

function foo() {
    bar = 4; // Note the lack of `var`
}

This has the same effect through the use of "implied globals"; but it will throw an error in ES5 strict mode, and is generally considered a bad practice (did the programmer mean to make it global, or did they simply accidentally omit var?).

Sign up to request clarification or add additional context in comments.

4 Comments

It will only throw an error in ES5 strict mode - in the non-strict mode of the ES5 specification it won't.
@Qantas94Heavy: Haha, thanks for the correction... my brain was writing "ES5 strict mode", but seems my keyboard had other ideas ;).
or one part of your brain was thinking strict and the other was eating it :-)
I feel like the reason why this is useful is completely missing here ("why not just make it global in the first place?"): Using a scope to setup your objects you can make sure that you won't make anything global that is supposed to be "private" (utility functions, private variables, …). With the assignment to window in the end you have easy control over what you actually export (= make global), plus you can easily change the way you are making it global (renaming, putting it into a different namespace, …).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.